#
db_sqlx_postgres/
errors.rs

    1// Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
    2// SPDX-FileCopyrightText: 2023 Aravinth Manivannan <realaravinth@batsense.net>
    3//
    4// SPDX-License-Identifier: AGPL-3.0-or-later
    5
    6//! Error-handling utilities
    7use std::borrow::Cow;
    8
    9use db_core::dev::*;
    10use sqlx::Error;
    11
    12/// map custom row not found error to DB error
    13pub fn map_row_not_found_err(e: Error, row_not_found: DBError) -> DBError {
    14    if let Error::RowNotFound = e {
    15        row_not_found
    16    } else {
    17        map_register_err(e)
    18    }
    19}
    20
    21/// map postgres errors to [DBError](DBError) types
    22pub fn map_register_err(e: Error) -> DBError {
    23    if let Error::Database(err) = e {
    24        if err.code() == Some(Cow::from("23505")) {
    25            let msg = err.message();
    26            println!("{}", msg);
    27            if msg.contains("mcaptcha_users_name_key") {
    28                DBError::UsernameTaken
    29            } else if msg.contains("mcaptcha_users_email_key") {
    30                DBError::EmailTaken
    31            } else if msg.contains("mcaptcha_users_secret_key") {
    32                DBError::SecretTaken
    33            } else if msg.contains("mcaptcha_config_key_key") {
    34                DBError::CaptchaKeyTaken
    35            } else {
    36                DBError::DBError(Box::new(Error::Database(err)))
    37            }
    38        } else {
    39            DBError::DBError(Box::new(Error::Database(err)))
    40        }
    41    } else {
    42        DBError::DBError(Box::new(e))
    43    }
    44}