Skip to main content

tds_driver/
error.rs

1//! Error module
2pub use crate::tds::codec::TokenError;
3pub use std::io::ErrorKind as IoErrorKind;
4use std::{borrow::Cow, convert::Infallible, io};
5use thiserror::Error;
6
7/// A unified error enum that contains several errors that might occurr during
8/// the lifecycle of this driver
9#[derive(Debug, Clone, Error, PartialEq, Eq)]
10pub enum Error {
11    #[error("An error occurred during the attempt of performing I/O: {}", message)]
12    /// An error occurred when performing I/O to the server.
13    Io {
14        /// A list specifying general categories of I/O error.
15        kind: IoErrorKind,
16        /// The error description.
17        message: String,
18    },
19    #[error("Protocol error: {}", _0)]
20    /// An error happened during the request or response parsing.
21    Protocol(Cow<'static, str>),
22    #[error("Encoding error: {}", _0)]
23    /// Server responded with encoding not supported.
24    Encoding(Cow<'static, str>),
25    #[error("Conversion error: {}", _0)]
26    /// Conversion failure from one type to another.
27    Conversion(Cow<'static, str>),
28    #[error("UTF-8 error")]
29    /// Tried to convert data to UTF-8 that was not valid.
30    Utf8,
31    #[error("UTF-16 error")]
32    /// Tried to convert data to UTF-16 that was not valid.
33    Utf16,
34    #[error("Error parsing an integer: {}", _0)]
35    /// Tried to parse an integer that was not an integer.
36    ParseInt(std::num::ParseIntError),
37    #[error("Token error: {}", _0)]
38    /// The first error the server returned for the request. The response's
39    /// other errors and info messages are on it: see
40    /// [`TokenError::other_errors`] and [`TokenError::info_messages`].
41    Server(TokenError),
42    #[error("Error forming TLS connection: {}", _0)]
43    /// An error in the TLS handshake.
44    Tls(String),
45    #[cfg(any(all(unix, feature = "integrated-auth-gssapi"), doc))]
46    #[cfg_attr(docsrs, doc(cfg(all(unix, feature = "integrated-auth-gssapi"))))]
47    /// An error from the GSSAPI library.
48    #[error("GSSAPI Error: {}", _0)]
49    Gssapi(String),
50    #[cfg(any(all(unix, feature = "sspi-rs"), doc))]
51    #[cfg_attr(docsrs, doc(cfg(all(unix, feature = "sspi-rs"))))]
52    /// An error from the `sspi` (sspi-rs) library.
53    #[error("sspi-rs Error: {}", _0)]
54    SspiRs(String),
55    #[error(
56        "Server requested a connection to an alternative address: `{}:{}`",
57        host,
58        port
59    )]
60    /// Server requested a connection to an alternative address.
61    Routing {
62        /// The requested hostname
63        host: String,
64        /// The requested port.
65        port: u16,
66    },
67    #[error("BULK UPLOAD input failure: {0}")]
68    /// Invalid input in Bulk Upload
69    BulkInput(Cow<'static, str>),
70}
71
72impl Error {
73    /// True, if the error was caused by a deadlock.
74    pub fn is_deadlock(&self) -> bool {
75        self.code().map(|c| c == 1205).unwrap_or(false)
76    }
77
78    /// Returns the error code, if the error originates from the
79    /// server.
80    pub fn code(&self) -> Option<u32> {
81        match self {
82            Error::Server(e) => Some(e.code()),
83            _ => None,
84        }
85    }
86}
87
88impl From<uuid::Error> for Error {
89    fn from(e: uuid::Error) -> Self {
90        Self::Conversion(format!("Error converting a Guid value {}", e).into())
91    }
92}
93
94#[cfg(feature = "native-tls")]
95impl From<async_native_tls::Error> for Error {
96    fn from(v: async_native_tls::Error) -> Self {
97        Error::Tls(format!("{}", v))
98    }
99}
100
101#[cfg(feature = "vendored-openssl")]
102impl From<opentls::Error> for Error {
103    fn from(v: opentls::Error) -> Self {
104        Error::Tls(format!("{}", v))
105    }
106}
107
108impl From<Infallible> for Error {
109    fn from(_: Infallible) -> Self {
110        unreachable!()
111    }
112}
113
114impl From<io::Error> for Error {
115    fn from(err: io::Error) -> Error {
116        Self::Io {
117            kind: err.kind(),
118            message: format!("{}", err),
119        }
120    }
121}
122
123impl From<std::num::ParseIntError> for Error {
124    fn from(err: std::num::ParseIntError) -> Error {
125        Error::ParseInt(err)
126    }
127}
128
129impl From<std::str::Utf8Error> for Error {
130    fn from(_: std::str::Utf8Error) -> Error {
131        Error::Utf8
132    }
133}
134
135impl From<std::string::FromUtf8Error> for Error {
136    fn from(_err: std::string::FromUtf8Error) -> Error {
137        Error::Utf8
138    }
139}
140
141impl From<std::string::FromUtf16Error> for Error {
142    fn from(_err: std::string::FromUtf16Error) -> Error {
143        Error::Utf16
144    }
145}
146
147impl From<connection_string::Error> for Error {
148    fn from(err: connection_string::Error) -> Error {
149        let err = Cow::Owned(format!("{}", err));
150        Error::Conversion(err)
151    }
152}
153
154#[cfg(all(unix, feature = "integrated-auth-gssapi"))]
155#[cfg_attr(docsrs, doc(cfg(all(unix, feature = "integrated-auth-gssapi"))))]
156impl From<libgssapi::error::Error> for Error {
157    fn from(err: libgssapi::error::Error) -> Error {
158        Error::Gssapi(format!("{}", err))
159    }
160}
161
162#[cfg(all(unix, feature = "sspi-rs"))]
163#[cfg_attr(docsrs, doc(cfg(all(unix, feature = "sspi-rs"))))]
164impl From<sspi::Error> for Error {
165    fn from(err: sspi::Error) -> Error {
166        Error::SspiRs(format!("{}", err))
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    fn token_error(code: u32) -> TokenError {
175        TokenError {
176            code,
177            state: 1,
178            class: 16,
179            message: "boom".to_string(),
180            server: "srv".into(),
181            procedure: "proc".into(),
182            line: 3,
183            related: None,
184        }
185    }
186
187    #[test]
188    fn code_and_is_deadlock() {
189        let deadlock = Error::Server(token_error(1205));
190        assert_eq!(deadlock.code(), Some(1205));
191        assert!(deadlock.is_deadlock());
192
193        let other = Error::Server(token_error(500));
194        assert_eq!(other.code(), Some(500));
195        assert!(!other.is_deadlock());
196
197        let non_server = Error::Utf8;
198        assert_eq!(non_server.code(), None);
199        assert!(!non_server.is_deadlock());
200    }
201
202    #[test]
203    fn display_variants() {
204        assert_eq!(
205            format!("{}", Error::Protocol("bad".into())),
206            "Protocol error: bad"
207        );
208        assert_eq!(
209            format!("{}", Error::Encoding("bad".into())),
210            "Encoding error: bad"
211        );
212        assert_eq!(
213            format!("{}", Error::Conversion("bad".into())),
214            "Conversion error: bad"
215        );
216        assert_eq!(format!("{}", Error::Utf8), "UTF-8 error");
217        assert_eq!(format!("{}", Error::Utf16), "UTF-16 error");
218        assert_eq!(
219            format!("{}", Error::BulkInput("bad".into())),
220            "BULK UPLOAD input failure: bad"
221        );
222
223        let routing = Error::Routing {
224            host: "host".to_string(),
225            port: 1234,
226        };
227        assert!(format!("{}", routing).contains("host:1234"));
228    }
229
230    #[test]
231    fn from_io_error() {
232        let io_err = io::Error::new(io::ErrorKind::UnexpectedEof, "eof");
233        let err: Error = io_err.into();
234        match err {
235            Error::Io { kind, message } => {
236                assert_eq!(kind, io::ErrorKind::UnexpectedEof);
237                assert!(message.contains("eof"));
238            }
239            _ => panic!("expected Io"),
240        }
241    }
242
243    #[test]
244    fn from_parse_int_error() {
245        let parse_err = "not-a-number".parse::<i32>().unwrap_err();
246        let err: Error = parse_err.into();
247        assert!(matches!(err, Error::ParseInt(_)));
248    }
249
250    #[test]
251    #[allow(invalid_from_utf8)] // intentionally-invalid bytes to exercise the error path
252    fn from_utf8_and_utf16_errors() {
253        let utf8_err = String::from_utf8(vec![0xff, 0xfe]).unwrap_err();
254        assert!(matches!(Error::from(utf8_err), Error::Utf8));
255
256        let invalid: &[u8] = &[0xff, 0xfe];
257        let str_utf8 = std::str::from_utf8(invalid).unwrap_err();
258        assert!(matches!(Error::from(str_utf8), Error::Utf8));
259
260        let utf16_err = String::from_utf16(&[0xd800]).unwrap_err();
261        assert!(matches!(Error::from(utf16_err), Error::Utf16));
262    }
263
264    #[test]
265    fn from_uuid_error() {
266        let uuid_err = uuid::Uuid::parse_str("not-a-uuid").unwrap_err();
267        assert!(matches!(Error::from(uuid_err), Error::Conversion(_)));
268    }
269
270    #[test]
271    fn equality_between_errors() {
272        assert_eq!(Error::Utf8, Error::Utf8);
273        assert_ne!(Error::Utf8, Error::Utf16);
274    }
275
276    #[test]
277    fn from_connection_string_error() {
278        let cs_err = connection_string::Error::new("bad connection string");
279        let err: Error = cs_err.into();
280        match err {
281            Error::Conversion(msg) => assert!(msg.contains("bad connection string")),
282            _ => panic!("expected Conversion"),
283        }
284    }
285
286    #[cfg(all(unix, feature = "sspi-rs"))]
287    #[test]
288    fn from_sspi_error() {
289        let sspi_err = sspi::Error::new(sspi::ErrorKind::InternalError, "sspi boom");
290        assert!(matches!(Error::from(sspi_err), Error::SspiRs(_)));
291    }
292
293    #[cfg(all(unix, feature = "integrated-auth-gssapi"))]
294    #[test]
295    fn from_gssapi_error() {
296        let gss_err = libgssapi::error::Error {
297            major: libgssapi::error::MajorFlags::empty(),
298            minor: 0,
299        };
300        assert!(matches!(Error::from(gss_err), Error::Gssapi(_)));
301    }
302}