httpd: implement `IntoResponse` for api error variants

Signed-off-by: xphoniex <dj.2dixx@gmail.com>
This commit is contained in:
xphoniex 2022-11-29 16:49:18 +00:00
parent b96f357c2e
commit 1b00e8a413
No known key found for this signature in database
GPG Key ID: 9FACFECE1E3B3994
1 changed files with 24 additions and 9 deletions

View File

@ -1,5 +1,7 @@
use axum::http;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
/// Errors relating to the HTTP backend.
#[derive(Debug, thiserror::Error)]
@ -73,16 +75,29 @@ pub enum Error {
StorageRef(#[from] radicle::storage::refs::Error),
}
impl Error {
pub fn status(&self) -> http::StatusCode {
http::StatusCode::INTERNAL_SERVER_ERROR
}
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
tracing::error!("{}", self);
let (status, msg) = match &self {
Error::NotFound => (StatusCode::NOT_FOUND, None),
Error::Auth(msg) => (StatusCode::BAD_REQUEST, Some(msg.to_string())),
Error::SiweParse(msg) => (StatusCode::BAD_REQUEST, Some(msg.to_string())),
Error::SiweVerification(msg) => (StatusCode::BAD_REQUEST, Some(msg.to_string())),
Error::Git2(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Some(e.message().to_owned()),
),
_ => {
tracing::error!("Error: {:?}", &self);
self.status().into_response()
(StatusCode::INTERNAL_SERVER_ERROR, None)
}
};
let body = Json(json!({
"error": msg.or_else(|| status.canonical_reason().map(|r| r.to_string())),
"code": status.as_u16()
}));
(status, body).into_response()
}
}