Skip to content

Commit

Permalink
Merge pull request #1 from 999eagle/main
Browse files Browse the repository at this point in the history
add custom error type
  • Loading branch information
LostQuasar authored Aug 27, 2024
2 parents ad9d015 + 5ccf3da commit 21c9b2f
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 9 deletions.
13 changes: 5 additions & 8 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::data_type::*;
use crate::{data_type::*, error::Error};
use reqwest::header;
use std::{error::Error, fmt::Debug};
use std::fmt::Debug;
use strum_macros::EnumString;

/// All methods contain an `Option<String>` to provide an alternate api key to use if it differs from the default
Expand Down Expand Up @@ -42,10 +42,7 @@ impl OpenShockAPI {
}

/// Gets user info from the provided API key, the default key from the instance is used if `None` is provided
pub async fn get_user_info(
&self,
api_key: Option<String>,
) -> Result<SelfResponse, Box<dyn Error>> {
pub async fn get_user_info(&self, api_key: Option<String>) -> Result<SelfResponse, Error> {
let resp = self
.client
.get(format!("{}/1/users/self", self.base_url))
Expand All @@ -65,7 +62,7 @@ impl OpenShockAPI {
&self,
source: ListShockerSource,
api_key: Option<String>,
) -> Result<Vec<ListShockersResponse>, Box<dyn Error>> {
) -> Result<Vec<ListShockersResponse>, Error> {
let resp = self
.client
.get(format!("{}/1/shockers/{:?}", self.base_url, source))
Expand All @@ -88,7 +85,7 @@ impl OpenShockAPI {
intensity: u8,
duration: u16,
api_key: Option<String>,
) -> Result<String, Box<dyn Error>> {
) -> Result<String, Error> {
match intensity {
1..=100 => {}
_ => {
Expand Down
36 changes: 36 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/// Error type for functions in this crate
#[derive(Debug)]
pub enum Error {
Reqwest(reqwest::Error),
Serde(serde_json::Error),
}

impl From<reqwest::Error> for Error {
fn from(value: reqwest::Error) -> Self {
Self::Reqwest(value)
}
}

impl From<serde_json::Error> for Error {
fn from(value: serde_json::Error) -> Self {
Self::Serde(value)
}
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Reqwest(e) => e.fmt(f),
Self::Serde(e) => e.fmt(f),
}
}
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Reqwest(e) => e.source(),
Self::Serde(e) => e.source(),
}
}
}
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@
//!

pub mod api;
pub mod data_type;
pub mod data_type;
pub mod error;

0 comments on commit 21c9b2f

Please sign in to comment.