From 2daab3052cab788a61036d5cc6440205b097b3d5 Mon Sep 17 00:00:00 2001 From: MegaBrutal Date: Fri, 15 Jul 2022 00:15:00 +0200 Subject: [PATCH 1/1] Gracefully handle non-existent canvas error --- src/main.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 373a401..9d1bd44 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,6 +40,31 @@ impl ResponseError for ImageError { } } +#[derive(Debug)] +enum CanvasError { + NotExists +} + +impl Display for CanvasError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Canvas Error: see error_response() for more details") + } +} + +impl ResponseError for CanvasError { + fn status_code(&self) -> StatusCode { + match &self { + CanvasError::NotExists => StatusCode::NOT_FOUND + } + } + + fn error_response(&self) -> HttpResponse { + match &self { + CanvasError::NotExists => HttpResponse::NotFound().body("Canvas does not exist.") + } + } +} + struct ToRgbIter<'a, T> where T: AsPrimitive { iter: Box<&'a mut dyn Iterator> } @@ -166,8 +191,8 @@ async fn img_pgen0(req: HttpRequest, canvas0: web::Data let tdim_y = 32 * scale; let img: RgbImage = { let canvas_option = &mut *canvas0.lock().unwrap(); - let canvas = canvas_option.take(); - let canvas = rgb_encode_to_canvas(canvas.expect("Canvas doesn't exist!"), percent_decode_str(&data).into_iter().borrow_mut())?; + let canvas = canvas_option.take().ok_or(CanvasError::NotExists)?; + let canvas = rgb_encode_to_canvas(canvas, percent_decode_str(&data).into_iter().borrow_mut())?; canvas_option.insert(canvas).img.clone() }; let img = resize(&img, tdim_x, tdim_y, FilterType::Nearest); -- 2.34.1