Handle error response compiler issues properly, use JSON for error response format

This commit is contained in:
2023-07-22 18:04:32 -05:00
parent 2704a214b9
commit 85401cbd3b
2 changed files with 22 additions and 8 deletions

View File

@@ -1,6 +1,8 @@
use axum::body::Full;
use axum::http::{StatusCode};
use axum::Json;
use axum::response::{IntoResponse, Response};
use serde::{Serialize, Deserialize};
pub enum TimeBannerError {
ParseError(String),
@@ -8,10 +10,18 @@ pub enum TimeBannerError {
RasterizeError(String),
}
pub fn get_error_response(error: TimeBannerError) -> (StatusCode, Full<String>) {
match error {
TimeBannerError::RenderError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, Full::from(format!("Template Could Not Be Rendered :: {}", msg))),
TimeBannerError::ParseError(msg) => (StatusCode::BAD_REQUEST, Full::from(format!("Failed to parse epoch :: {}", msg))),
TimeBannerError::RasterizeError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, Full::from(format!("Failed to rasterize :: {}", msg)))
#[derive(Serialize, Deserialize)]
pub struct ErrorResponse {
code: u16,
message: String,
}
pub fn get_error_response(error: TimeBannerError) -> (StatusCode, Json<ErrorResponse>) {
let (code, message) = match error {
TimeBannerError::RenderError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, format!("RenderError :: {}", msg)),
TimeBannerError::ParseError(msg) => (StatusCode::BAD_REQUEST, format!("ParserError :: {}", msg)),
TimeBannerError::RasterizeError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, format!("RasertizeError :: {}", msg))
};
(code, Json(ErrorResponse { code: code.as_u16(), message }))
}

View File

@@ -51,11 +51,15 @@ pub async fn implicit_handler(Path(path): Path<String>) -> impl IntoResponse {
// Parse epoch
let parsed_epoch = raw_time.parse::<i64>();
if parsed_epoch.is_err() {
return (StatusCode::BAD_REQUEST, Full::from(format!("Failed to parse epoch :: {}", parsed_epoch.unwrap_err()))).into_response();
return get_error_response(TimeBannerError::ParseError("Input could not be parsed into integer.".to_string())).into_response();
}
// Convert epoch to DateTime
let naive_time = NaiveDateTime::from_timestamp_opt(parsed_epoch.unwrap(), 0);
if naive_time.is_none() {
return get_error_response(TimeBannerError::ParseError("Input was not a valid DateTime".to_string())).into_response();
}
let utc_time = DateTime::<Utc>::from_utc(naive_time.unwrap(), Utc);
// Build context for rendering
@@ -75,7 +79,7 @@ pub async fn implicit_handler(Path(path): Path<String>) -> impl IntoResponse {
.body(Full::from(
format!("Template Could Not Be Rendered :: {}", rendered_template.err().unwrap())
))
.unwrap();
.unwrap().into_response();
}
let rasterize_result = handle_rasterize(rendered_template.unwrap(), extension);