From 55ffd06be14e74f086a244d25b2c4eca94ba35a5 Mon Sep 17 00:00:00 2001 From: Jose Quintana Date: Thu, 1 Jul 2021 15:25:58 +0200 Subject: [PATCH] refactor: handle potencial panic for 404/50x error page responses --- src/error_page.rs | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/src/error_page.rs b/src/error_page.rs index 2777229..88cbde9 100644 --- a/src/error_page.rs +++ b/src/error_page.rs @@ -7,10 +7,11 @@ use crate::error::Result; pub static PAGE_404: OnceCell = OnceCell::new(); pub static PAGE_50X: OnceCell = OnceCell::new(); +/// It returns a HTTP error response which also handles available `404` or `50x` HTML content. pub fn get_error_response(method: &Method, status_code: &StatusCode) -> Result> { - tracing::warn!(method = ?method, status = status_code.as_u16(), error = ?status_code.to_string()); + tracing::warn!(method = ?method, status = status_code.as_u16(), error = ?status_code.to_owned()); - // Check for 4xx and 50x status codes + // Check for 4xx and 50x status codes and handle their corresponding HTML content let mut error_page_content = String::new(); let status_code = match status_code { // 4xx @@ -32,13 +33,17 @@ pub fn get_error_response(method: &Method, status_code: &StatusCode) -> Result { - // Extra check for 404 status code and HTML content + // Extra check for 404 status code and its HTML content if status_code == &StatusCode::NOT_FOUND { - // TODO: handle this potential panic properly - error_page_content = PAGE_404 - .get() - .expect("PAGE_404 contant is not initialized") - .to_string(); + error_page_content = match PAGE_404.get() { + Some(s) => s.to_owned(), + None => { + tracing::error!( + "404 error page content is not accessible or `PAGE_404` uninitialized" + ); + String::new() + } + }; } status_code } @@ -52,12 +57,16 @@ pub fn get_error_response(method: &Method, status_code: &StatusCode) -> Result { - // HTML content for error status codes 50x - // TODO: handle this potential panic properly - error_page_content = PAGE_50X - .get() - .expect("PAGE_50X contant is not initialized") - .to_string(); + // HTML content for error status codes 50x and their HTML content + error_page_content = match PAGE_50X.get() { + Some(s) => s.to_owned(), + None => { + tracing::error!( + "50x error page content is not accessible or `PAGE_50X` uninitialized" + ); + String::new() + } + }; status_code } // other status codes -- libgit2 1.7.2