feat: db errors

This commit is contained in:
2026-05-11 11:33:12 +02:00
parent b77715268d
commit 5aa7a6e7e1
5 changed files with 35 additions and 5 deletions
+2 -1
View File
@@ -1,7 +1,8 @@
use super::errors::DbError;
use sqlx::PgPool;
use uuid::Uuid;
pub async fn update_last_access(pool: &PgPool, api_key_id: Uuid) -> Result<(), sqlx::Error> {
pub async fn update_last_access(pool: &PgPool, api_key_id: Uuid) -> Result<(), DbError> {
sqlx::query!(
r#"
UPDATE auth.api_key
+21
View File
@@ -0,0 +1,21 @@
use axum::http::StatusCode;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DbError {
#[error("database connection error")]
Connection(#[from] sqlx::Error),
#[error("database timeout")]
Timeout,
}
pub fn _into_http_response(e: DbError) -> (StatusCode, String) {
match e {
DbError::Connection(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
"database connection error".to_string(),
),
DbError::Timeout => (StatusCode::REQUEST_TIMEOUT, "database timeout".to_string()),
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod api_key;
pub mod errors;
pub mod pool;
pub mod user;
+7 -2
View File
@@ -1,7 +1,8 @@
use super::errors::DbError;
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::time::Duration;
pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
pub async fn create_pool(database_url: &str) -> Result<PgPool, DbError> {
PgPoolOptions::new()
.max_connections(10)
.acquire_timeout(Duration::from_secs(5))
@@ -9,6 +10,10 @@ pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
.await
.map_err(|err| {
tracing::error!("Postgres connection error: {:?}", err);
err
match err {
sqlx::Error::PoolTimedOut => DbError::Timeout,
_ => DbError::Connection(err),
}
})
}
+4 -2
View File
@@ -1,7 +1,8 @@
use super::errors::DbError;
use sqlx::PgPool;
use uuid::Uuid;
pub async fn ensure_user_exists(pool: &PgPool, user_id: Uuid) -> Result<(), sqlx::Error> {
pub async fn ensure_user_exists(pool: &PgPool, user_id: Uuid) -> Result<(), DbError> {
sqlx::query!(
r#"
INSERT INTO auth.app_user (id)
@@ -11,7 +12,8 @@ pub async fn ensure_user_exists(pool: &PgPool, user_id: Uuid) -> Result<(), sqlx
user_id
)
.execute(pool)
.await?;
.await
.map_err(DbError::Connection)?;
Ok(())
}