db_sqlx_maria/
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("23000")) {
25            let msg = err.message();
26            if msg.contains("for key 'name'") {
27                DBError::UsernameTaken
28            } else if msg.contains("for key 'email'") {
29                DBError::EmailTaken
30            } else if msg.contains("for key 'secret'") {
31                DBError::SecretTaken
32            } else if msg.contains("for key 'captcha_key'") {
33                DBError::CaptchaKeyTaken
34            } else {
35                DBError::DBError(Box::new(Error::Database(err)))
36            }
37        } else {
38            DBError::DBError(Box::new(Error::Database(err)))
39        }
40    } else {
41        DBError::DBError(Box::new(e))
42    }
43}