refactor errors

This commit is contained in:
Hamcha 2023-06-29 01:21:45 +02:00
parent 68dce235c1
commit 06e8494c01
Signed by: hamcha
GPG key ID: 1669C533B8CF6D89
2 changed files with 28 additions and 27 deletions

23
src/error.rs Normal file
View file

@ -0,0 +1,23 @@
use anyhow::anyhow;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
pub struct InternalError(anyhow::Error);
impl IntoResponse for InternalError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
impl From<sqlx::Error> for InternalError {
fn from(value: sqlx::Error) -> Self {
InternalError(anyhow!("Database error: {}", value))
}
}

View file

@ -1,13 +1,9 @@
mod content;
mod error;
use anyhow::{anyhow, Result};
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Router, Server,
};
use anyhow::Result;
use axum::{extract::State, routing::get, Router, Server};
use error::InternalError;
use figment::{
providers::{Env, Format, Serialized, Toml},
Figment,
@ -33,29 +29,11 @@ impl Default for Config {
}
}
struct GenericError(anyhow::Error);
impl IntoResponse for GenericError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
impl From<sqlx::Error> for GenericError {
fn from(value: sqlx::Error) -> Self {
GenericError(anyhow!("Database error: {}", value))
}
}
struct AppState {
database: Pool<Postgres>,
}
async fn root(State(state): State<Arc<AppState>>) -> Result<String, GenericError> {
async fn root(State(state): State<Arc<AppState>>) -> Result<String, InternalError> {
let select_query: sqlx::query::QueryAs<'_, _, Page, _> =
sqlx::query_as::<_, Page>("SELECT * FROM pages");
let page: Page = select_query.fetch_one(&state.database).await?;