|
1 | 1 | use anyhow; |
| 2 | +use axum::{ |
| 3 | + Json, |
| 4 | + http::StatusCode, |
| 5 | + response::{IntoResponse, Response}, |
| 6 | +}; |
| 7 | +use serde::Serialize; |
2 | 8 | use std::{ |
3 | 9 | error::Error, |
4 | 10 | fmt::{Debug, Display}, |
@@ -134,3 +140,73 @@ impl<'a, T> SharedResultExtRef<'a, T> for &'a Result<T, SharedError> { |
134 | 140 | pub fn invariance_violation() -> anyhow::Error { |
135 | 141 | anyhow::anyhow!("Invariance violation") |
136 | 142 | } |
| 143 | + |
| 144 | +// API Error types for HTTP responses |
| 145 | + |
| 146 | +#[derive(Debug)] |
| 147 | +pub struct ApiError { |
| 148 | + pub err: anyhow::Error, |
| 149 | + pub status_code: StatusCode, |
| 150 | +} |
| 151 | + |
| 152 | +impl ApiError { |
| 153 | + pub fn new(message: &str, status_code: StatusCode) -> Self { |
| 154 | + Self { |
| 155 | + err: anyhow::anyhow!("{}", message), |
| 156 | + status_code, |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +impl Display for ApiError { |
| 162 | + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 163 | + Display::fmt(&self.err, f) |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +impl Error for ApiError { |
| 168 | + fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 169 | + self.err.source() |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +#[derive(Serialize)] |
| 174 | +struct ErrorResponse { |
| 175 | + error: String, |
| 176 | +} |
| 177 | + |
| 178 | +impl IntoResponse for ApiError { |
| 179 | + fn into_response(self) -> Response { |
| 180 | + log::debug!("Internal server error:\n{:?}", self.err); |
| 181 | + let error_response = ErrorResponse { |
| 182 | + error: format!("{:?}", self.err), |
| 183 | + }; |
| 184 | + (self.status_code, Json(error_response)).into_response() |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +impl From<anyhow::Error> for ApiError { |
| 189 | + fn from(err: anyhow::Error) -> ApiError { |
| 190 | + if err.is::<ApiError>() { |
| 191 | + return err.downcast::<ApiError>().unwrap(); |
| 192 | + } |
| 193 | + Self { |
| 194 | + err, |
| 195 | + status_code: StatusCode::INTERNAL_SERVER_ERROR, |
| 196 | + } |
| 197 | + } |
| 198 | +} |
| 199 | + |
| 200 | +#[macro_export] |
| 201 | +macro_rules! api_bail { |
| 202 | + ( $fmt:literal $(, $($arg:tt)*)?) => { |
| 203 | + return Err($crate::error::ApiError::new(&format!($fmt $(, $($arg)*)?), axum::http::StatusCode::BAD_REQUEST).into()) |
| 204 | + }; |
| 205 | +} |
| 206 | + |
| 207 | +#[macro_export] |
| 208 | +macro_rules! api_error { |
| 209 | + ( $fmt:literal $(, $($arg:tt)*)?) => { |
| 210 | + $crate::error::ApiError::new(&format!($fmt $(, $($arg)*)?), axum::http::StatusCode::BAD_REQUEST) |
| 211 | + }; |
| 212 | +} |
0 commit comments