use std::time::Duration;
use serde::Deserialize;
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct ProblemDetails {
#[serde(rename = "type", default)]
problem_type: Option<String>,
#[serde(default)]
title: Option<String>,
#[serde(default)]
status: Option<u16>,
#[serde(default)]
detail: Option<String>,
#[serde(default)]
code: Option<String>,
}
impl ProblemDetails {
pub fn problem_type(&self) -> Option<&str> {
self.problem_type.as_deref()
}
pub fn title(&self) -> Option<&str> {
self.title.as_deref()
}
pub fn status(&self) -> Option<u16> {
self.status
}
pub fn detail(&self) -> Option<&str> {
self.detail.as_deref()
}
pub fn code(&self) -> Option<&str> {
self.code.as_deref()
}
pub(crate) fn fallback(status: u16, raw_body: &str) -> Self {
const MAX_LEN: usize = 500;
let detail = if raw_body.is_empty() {
None
} else {
Some(raw_body.chars().take(MAX_LEN).collect())
};
Self {
problem_type: None,
title: None,
status: Some(status),
detail,
code: None,
}
}
}
impl std::fmt::Display for ProblemDetails {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let message = self
.detail
.as_deref()
.or(self.title.as_deref())
.unwrap_or("erreur sans détail");
f.write_str(message)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CarbonFrError {
#[error("erreur de transport : {0}")]
Transport(#[from] reqwest::Error),
#[error("erreur API carbon-fr ({status}) : {problem}")]
#[non_exhaustive]
Api {
status: u16,
problem: ProblemDetails,
},
#[error("échec de décodage de la réponse : {0}")]
Decode(String),
#[error("configuration du client invalide : {0}")]
Config(String),
#[error("délai dépassé ({0:?})")]
Timeout(Duration),
}
impl CarbonFrError {
pub fn code(&self) -> Option<&str> {
match self {
CarbonFrError::Api { problem, .. } => problem.code(),
_ => None,
}
}
pub fn status(&self) -> Option<u16> {
match self {
CarbonFrError::Api { status, .. } => Some(*status),
_ => None,
}
}
}