Last active: 10 months ago
Axum custom app error.
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use log::error;
use serde_json::json;
#[derive(thiserror::Error, Debug)]
pub enum AppError {
#[error("server internal error {0}")]
InternalServerError(#[from] anyhow::Error),
}
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status_code, err_message): (StatusCode, _) = match self {
AppError::InternalServerError(err) => {
error!("{}", err);
(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong")
}
};
let body = Json(json!({
"error": err_message
}));
(status_code, body).into_response()
}
}
pub type RheaResult<T, E = AppError> = Result<T, E>;
use crate::error::AppError;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use log::error;
use serde_json::json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum RouteError {
#[error("server internal error {0}")]
InternalServerError(#[from] anyhow::Error),
#[error("request validate failed {0}")]
ValidationError(String),
}
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for RouteError {
fn into_response(self) -> Response {
use RouteError::*;
let (status_code, err_message) = match self {
InternalServerError(err) => {
return AppError::InternalServerError(err).into_response();
}
ValidationError(res) => {
error!("{}", res);
(StatusCode::UNAUTHORIZED, res)
}
};
let body = Json(json!({
"error": err_message
}));
(status_code, body).into_response()
}
}
pub type RouteResult<T, E = RouteError> = Result<T, E>;