rbdc_mysql/
error.rs

1use crate::protocol::response::ErrPacket;
2use std::error::Error;
3use std::fmt::{self, Debug, Display, Formatter};
4
5/// An error returned from the MySQL database.
6pub struct MySqlDatabaseError(pub(super) ErrPacket);
7
8impl MySqlDatabaseError {
9    /// The [SQLSTATE](https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html) code for this error.
10    pub fn code(&self) -> Option<&str> {
11        self.0.sql_state.as_deref()
12    }
13
14    /// The [number](https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html)
15    /// for this error.
16    ///
17    /// MySQL tends to use SQLSTATE as a general error category, and the error number as a more
18    /// granular indication of the error.
19    pub fn number(&self) -> u16 {
20        self.0.error_code
21    }
22
23    /// The human-readable error message.
24    pub fn message(&self) -> &str {
25        &self.0.error_message
26    }
27}
28
29impl Debug for MySqlDatabaseError {
30    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
31        f.debug_struct("MySqlDatabaseError")
32            .field("code", &self.code())
33            .field("number", &self.number())
34            .field("message", &self.message())
35            .finish()
36    }
37}
38
39impl Display for MySqlDatabaseError {
40    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
41        if let Some(code) = &self.code() {
42            write!(f, "{} ({}): {}", self.number(), code, self.message())
43        } else {
44            write!(f, "{}: {}", self.number(), self.message())
45        }
46    }
47}
48
49impl Error for MySqlDatabaseError {}
50
51impl MySqlDatabaseError {
52    #[doc(hidden)]
53    fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {
54        self
55    }
56
57    #[doc(hidden)]
58    fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {
59        self
60    }
61
62    #[doc(hidden)]
63    fn into_error(self: Box<Self>) -> Box<dyn Error + Send + Sync + 'static> {
64        self
65    }
66}
67
68impl From<MySqlDatabaseError> for rbdc::Error {
69    fn from(arg: MySqlDatabaseError) -> Self {
70        rbdc::Error::from(arg.to_string())
71    }
72}