From: MegaBrutal Date: Thu, 14 Jul 2022 22:15:00 +0000 (+0200) Subject: Gracefully handle non-existent canvas error X-Git-Url: http://git.megabrutal.com/?a=commitdiff_plain;h=2daab3052cab788a61036d5cc6440205b097b3d5;hp=670c07e56eae02b24f0d27898ae4c2046e66bdc0;p=litoprism.git Gracefully handle non-existent canvas error --- 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);