Skip to content

Commit

Permalink
add description field to error, more info in error message
Browse files Browse the repository at this point in the history
  • Loading branch information
kilork committed Sep 3, 2024
1 parent bec3a02 commit d4e6827
Showing 1 changed file with 40 additions and 18 deletions.
58 changes: 40 additions & 18 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{borrow::Cow, error::Error, fmt::Display};

use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fmt::Display;

#[derive(Debug)]
pub enum KeycloakError {
Expand All @@ -12,31 +12,53 @@ pub enum KeycloakError {
},
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct KeycloakHttpError {
pub error: Option<String>,
#[serde(rename = "errorMessage")]
pub error_message: Option<String>,
}

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

impl Error for KeycloakError {
fn description(&self) -> &str {
"keycloak error"
}
impl Error for KeycloakError {}

fn cause(&self) -> Option<&dyn Error> {
None
impl Display for KeycloakError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KeycloakError::ReqwestFailure(e) => write!(f, "keycloak error (reqwest): {e}"),
KeycloakError::HttpFailure { status, body, text } => write!(
f,
"keycloak error (rest): {status} {}",
body.as_ref()
.and_then(|e| e.message())
.unwrap_or_else(|| Cow::from(text))
),
}
}
}

impl Display for KeycloakError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "keycloak error")
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct KeycloakHttpError {
pub error: Option<String>,
pub error_description: Option<String>,
#[serde(rename = "errorMessage")]
pub error_message: Option<String>,
}

impl KeycloakHttpError {
pub fn message(&self) -> Option<Cow<'_, str>> {
self.error_message
.as_deref()
.map(Cow::from)
.or_else(|| {
self.error
.as_deref()
.map(|error| {
format!(
"{} [{error}]",
self.error_description.as_deref().unwrap_or("null")
)
})
.map(Cow::from)
})
.or_else(|| self.error_description.as_deref().map(Cow::from))
}
}

0 comments on commit d4e6827

Please sign in to comment.