1use std;
4use std::convert::From;
5use std::error::Error;
6use std::fmt;
7use std::io;
8use std::str::Utf8Error;
9
10pub type WebSocketResult<T> = Result<T, WebSocketError>;
12
13#[cfg(feature = "async")]
16pub mod r#async {
17 use super::WebSocketError;
18 use futures::Future;
19
20 pub type WebSocketFuture<I> = Box<dyn Future<Item = I, Error = WebSocketError> + Send>;
23}
24
25#[derive(Debug)]
27pub enum WebSocketError {
28 ProtocolError(&'static str),
30 DataFrameError(&'static str),
32 NoDataAvailable,
34 IoError(io::Error),
36 Utf8Error(Utf8Error),
38 Other(Box<dyn std::error::Error + Send + Sync + 'static>),
40}
41
42impl fmt::Display for WebSocketError {
43 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
44 fmt.write_str("WebSocketError: ")?;
45 match self {
46 WebSocketError::ProtocolError(_) => fmt.write_str("WebSocket protocol error"),
47 WebSocketError::DataFrameError(_) => fmt.write_str("WebSocket data frame error"),
48 WebSocketError::NoDataAvailable => fmt.write_str("No data available"),
49 WebSocketError::IoError(_) => fmt.write_str("I/O failure"),
50 WebSocketError::Utf8Error(_) => fmt.write_str("UTF-8 failure"),
51 WebSocketError::Other(x) => x.fmt(fmt),
52 }
53 }
54}
55
56impl Error for WebSocketError {
57 fn source(&self) -> Option<&(dyn Error + 'static)> {
58 match *self {
59 WebSocketError::IoError(ref error) => Some(error),
60 WebSocketError::Utf8Error(ref error) => Some(error),
61 WebSocketError::Other(ref error) => error.source(),
62 _ => None,
63 }
64 }
65}
66
67impl From<io::Error> for WebSocketError {
68 fn from(err: io::Error) -> WebSocketError {
69 if err.kind() == io::ErrorKind::UnexpectedEof {
70 return WebSocketError::NoDataAvailable;
71 }
72 WebSocketError::IoError(err)
73 }
74}
75
76impl From<Utf8Error> for WebSocketError {
77 fn from(err: Utf8Error) -> WebSocketError {
78 WebSocketError::Utf8Error(err)
79 }
80}