Improved error handling a bit

This commit is contained in:
Slatian 2023-02-23 21:25:24 +01:00
parent 67b2103f5a
commit 6e1d3c02ef
2 changed files with 23 additions and 2 deletions

View File

@ -239,6 +239,7 @@ async fn main() {
.route("/ip/:address", get(handle_ip_route_with_path))
.route("/ua", get(user_agent_handler))
.route("/hi", get(hello_world_handler))
.fallback(not_found_handler)
.with_state(shared_state)
.layer(
ServiceBuilder::new()
@ -290,6 +291,18 @@ async fn hello_world_handler(
) -> Response {
let state = Arc::clone(&arc_state);
state.templating_engine.render_view(
&settings,
&View::NotFound,
).await
}
async fn not_found_handler(
State(arc_state): State<Arc<ServiceSharedState>>,
Extension(settings): Extension<TemplateSettings>,
) -> Response {
let state = Arc::clone(&arc_state);
state.templating_engine.render_view(
&settings,
&View::Message{
@ -299,6 +312,7 @@ async fn hello_world_handler(
).await
}
async fn user_agent_handler(
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
) -> String {

View File

@ -87,7 +87,7 @@ impl Engine {
settings: &TemplateSettings,
view: &View,
) -> Response {
match settings.format {
let mut response = match settings.format {
ResponseFormat::TextHtml => {
let template_name = view.template_name();
@ -103,7 +103,9 @@ impl Engine {
Ok(html) => Html(html).into_response(),
Err(e) => {
println!("There was an error while rendering index.html: {e:?}");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
let mut response = "Template error, contact owner or see logs.".into_response();
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
return response;
}
}
}
@ -119,6 +121,11 @@ impl Engine {
_ => Json(view).into_response(),
}
}
};
match view {
View::NotFound => *response.status_mut() = StatusCode::NOT_FOUND,
_ => {},
}
response
}
}