Error handling refactor and 500 page/message templates
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
use crate::startup::AppState;
|
||||
use crate::{routes::AppError, startup::AppState};
|
||||
use anyhow::Context;
|
||||
use askama::Template;
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::{Html, IntoResponse, Response},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use reqwest::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -40,17 +40,13 @@ pub async fn list_posts(
|
||||
State(AppState {
|
||||
connection_pool, ..
|
||||
}): State<AppState>,
|
||||
) -> Response {
|
||||
match get_latest_posts(&connection_pool, 5).await {
|
||||
Err(e) => {
|
||||
tracing::error!("Could not fetch latest posts: {}", e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
}
|
||||
Ok(posts) => {
|
||||
let template = PostsTemplate { posts };
|
||||
Html(template.render().unwrap()).into_response()
|
||||
}
|
||||
}
|
||||
) -> Result<Response, AppError> {
|
||||
let posts = get_latest_posts(&connection_pool, 5)
|
||||
.await
|
||||
.context("Could not fetch latest posts")
|
||||
.map_err(AppError::unexpected_page)?;
|
||||
let template = PostsTemplate { posts };
|
||||
Ok(Html(template.render().unwrap()).into_response())
|
||||
}
|
||||
|
||||
async fn get_latest_posts(connection_pool: &PgPool, n: i64) -> Result<Vec<PostEntry>, sqlx::Error> {
|
||||
@@ -74,17 +70,13 @@ pub async fn see_post(
|
||||
connection_pool, ..
|
||||
}): State<AppState>,
|
||||
Path(post_id): Path<Uuid>,
|
||||
) -> Response {
|
||||
match get_post(&connection_pool, post_id).await {
|
||||
Err(e) => {
|
||||
tracing::error!("Could not fetch post #{}: {}", post_id, e);
|
||||
StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
}
|
||||
Ok(post) => {
|
||||
let template = PostTemplate { post };
|
||||
Html(template.render().unwrap()).into_response()
|
||||
}
|
||||
}
|
||||
) -> Result<Response, AppError> {
|
||||
let post = get_post(&connection_pool, post_id)
|
||||
.await
|
||||
.context(format!("Failed to fetch post #{}", post_id))
|
||||
.map_err(AppError::unexpected_page)?;
|
||||
let template = PostTemplate { post };
|
||||
Ok(Html(template.render().unwrap()).into_response())
|
||||
}
|
||||
|
||||
async fn get_post(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry, sqlx::Error> {
|
||||
|
||||
Reference in New Issue
Block a user