Re-implementing the API

This commit is contained in:
2024-12-19 13:50:31 -05:00
parent 9344979d72
commit 4a18af9014
17 changed files with 486 additions and 152 deletions

View File

@@ -1,4 +1,7 @@
use std::fmt;
use axum::http::StatusCode;
use axum::Json;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
pub type SirenResult<T> = Result<T, Error>;
@@ -6,21 +9,44 @@ pub type SirenResult<T> = Result<T, Error>;
#[derive(Debug, Deserialize, Serialize)]
pub struct Error {
pub status: u16,
pub message: String,
pub details: String,
}
impl Error {
pub fn new(error_status_code: u16, error_message: String) -> Self {
Self {
status: error_status_code,
message: error_message,
details: error_message,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.message.as_str())
f.write_str(self.details.as_str())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
&self.details
}
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
// Create a JSON response with the structured error
let body = Json(serde_json::json!({
"error": {
"status": self.status,
"details": self.details,
}
}));
// Return the response with the proper status and error body
(status, body).into_response()
}
}
@@ -30,6 +56,18 @@ impl From<std::io::Error> for Error {
}
}
impl From<StatusCode> for Error {
fn from(status: StatusCode) -> Self {
Error {
status: status.as_u16(),
details: status
.canonical_reason()
.unwrap_or("Unknown error")
.to_string(),
}
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(error: std::string::FromUtf8Error) -> Self {
Self::new(500, format!("Unknown from utf8 error: {}", error))