From 5ccf3dabc0278bae445ac067ae6ff41b2851360d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=9B=A7-440729=20=5Bsophie=5D?= Date: Wed, 14 Aug 2024 17:57:37 +0200 Subject: [PATCH] add custom error type --- src/api.rs | 13 +++++-------- src/error.rs | 36 ++++++++++++++++++++++++++++++++++++ src/lib.rs | 3 ++- 3 files changed, 43 insertions(+), 9 deletions(-) create mode 100644 src/error.rs diff --git a/src/api.rs b/src/api.rs index 93d9145..e280280 100644 --- a/src/api.rs +++ b/src/api.rs @@ -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` to provide an alternate api key to use if it differs from the default @@ -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, - ) -> Result> { + pub async fn get_user_info(&self, api_key: Option) -> Result { let resp = self .client .get(format!("{}/1/users/self", self.base_url)) @@ -65,7 +62,7 @@ impl OpenShockAPI { &self, source: ListShockerSource, api_key: Option, - ) -> Result, Box> { + ) -> Result, Error> { let resp = self .client .get(format!("{}/1/shockers/{:?}", self.base_url, source)) @@ -88,7 +85,7 @@ impl OpenShockAPI { intensity: u8, duration: u16, api_key: Option, - ) -> Result> { + ) -> Result { match intensity { 1..=100 => {} _ => { diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..e439aae --- /dev/null +++ b/src/error.rs @@ -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 for Error { + fn from(value: reqwest::Error) -> Self { + Self::Reqwest(value) + } +} + +impl From 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(), + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 239db49..188422c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,4 +29,5 @@ //! pub mod api; -pub mod data_type; \ No newline at end of file +pub mod data_type; +pub mod error;