Skip to main content

actix_http/
error.rs

1//! Error and Result module
2
3use std::{error::Error as StdError, fmt, io, str::Utf8Error, string::FromUtf8Error};
4
5use derive_more::{Display, Error, From};
6pub use http::{status::InvalidStatusCode, Error as HttpError};
7use http::{uri::InvalidUri, StatusCode};
8
9use crate::{body::BoxBody, Response};
10
11pub struct Error {
12    inner: Box<ErrorInner>,
13}
14
15pub(crate) struct ErrorInner {
16    #[allow(dead_code)]
17    kind: Kind,
18    cause: Option<Box<dyn StdError>>,
19}
20
21impl Error {
22    fn new(kind: Kind) -> Self {
23        Self {
24            inner: Box::new(ErrorInner { kind, cause: None }),
25        }
26    }
27
28    pub(crate) fn with_cause(mut self, cause: impl Into<Box<dyn StdError>>) -> Self {
29        self.inner.cause = Some(cause.into());
30        self
31    }
32
33    pub(crate) fn new_http() -> Self {
34        Self::new(Kind::Http)
35    }
36
37    pub(crate) fn new_parse() -> Self {
38        Self::new(Kind::Parse)
39    }
40
41    pub(crate) fn new_payload() -> Self {
42        Self::new(Kind::Payload)
43    }
44
45    pub(crate) fn new_body() -> Self {
46        Self::new(Kind::Body)
47    }
48
49    pub(crate) fn new_send_response() -> Self {
50        Self::new(Kind::SendResponse)
51    }
52
53    #[allow(unused)] // available for future use
54    pub(crate) fn new_io() -> Self {
55        Self::new(Kind::Io)
56    }
57
58    #[allow(unused)] // used in encoder behind feature flag so ignore unused warning
59    pub(crate) fn new_encoder() -> Self {
60        Self::new(Kind::Encoder)
61    }
62
63    #[allow(unused)] // used with `ws` feature flag
64    pub(crate) fn new_ws() -> Self {
65        Self::new(Kind::Ws)
66    }
67}
68
69impl From<Error> for Response<BoxBody> {
70    fn from(err: Error) -> Self {
71        // TODO: more appropriate error status codes, usage assessment needed
72        let status_code = match err.inner.kind {
73            Kind::Parse => StatusCode::BAD_REQUEST,
74            _ => StatusCode::INTERNAL_SERVER_ERROR,
75        };
76
77        Response::new(status_code).set_body(BoxBody::new(err.to_string()))
78    }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
82pub(crate) enum Kind {
83    #[display("Error processing HTTP")]
84    Http,
85
86    #[display("Error parsing HTTP message")]
87    Parse,
88
89    #[display("Request payload read error")]
90    Payload,
91
92    #[display("Response body write error")]
93    Body,
94
95    #[display("Send response error")]
96    SendResponse,
97
98    #[display("Error in WebSocket process")]
99    Ws,
100
101    #[display("Connection error")]
102    Io,
103
104    #[display("Encoder error")]
105    Encoder,
106}
107
108impl fmt::Debug for Error {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        f.debug_struct("actix_http::Error")
111            .field("kind", &self.inner.kind)
112            .field("cause", &self.inner.cause)
113            .finish()
114    }
115}
116
117impl fmt::Display for Error {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        match self.inner.cause.as_ref() {
120            Some(err) => write!(f, "{}: {err}", self.inner.kind),
121            None => write!(f, "{}", self.inner.kind),
122        }
123    }
124}
125
126impl StdError for Error {
127    fn source(&self) -> Option<&(dyn StdError + 'static)> {
128        self.inner.cause.as_ref().map(Box::as_ref)
129    }
130}
131
132impl From<std::convert::Infallible> for Error {
133    fn from(err: std::convert::Infallible) -> Self {
134        match err {}
135    }
136}
137
138impl From<HttpError> for Error {
139    fn from(err: HttpError) -> Self {
140        Self::new_http().with_cause(err)
141    }
142}
143
144#[cfg(feature = "ws")]
145impl From<crate::ws::HandshakeError> for Error {
146    fn from(err: crate::ws::HandshakeError) -> Self {
147        Self::new_ws().with_cause(err)
148    }
149}
150
151#[cfg(feature = "ws")]
152impl From<crate::ws::ProtocolError> for Error {
153    fn from(err: crate::ws::ProtocolError) -> Self {
154        Self::new_ws().with_cause(err)
155    }
156}
157
158/// A set of errors that can occur during parsing HTTP streams.
159#[derive(Debug, Display, Error)]
160#[non_exhaustive]
161pub enum ParseError {
162    /// An invalid `Method`, such as `GE.T`.
163    #[display("Invalid method specified")]
164    Method,
165
166    /// An invalid `Uri`, such as `exam ple.domain`.
167    #[display("URI error: {}", _0)]
168    Uri(InvalidUri),
169
170    /// The request target uses a form that HTTP does not allow for this request.
171    #[display("Invalid request target")]
172    RequestTarget,
173
174    /// An invalid `HttpVersion`, such as `HTP/1.1`
175    #[display("Invalid HTTP version specified")]
176    Version,
177
178    /// An invalid `Header`.
179    #[display("Invalid Header provided")]
180    Header,
181
182    /// A message head is too large to be reasonable.
183    #[display("Message head is too large")]
184    TooLarge,
185
186    /// A message reached EOF, but is not complete.
187    #[display("Message is incomplete")]
188    Incomplete,
189
190    /// An invalid `Status`, such as `1337 ELITE`.
191    #[display("Invalid status provided")]
192    Status,
193
194    /// A timeout occurred waiting for an IO event.
195    #[allow(dead_code)]
196    #[display("Timeout")]
197    Timeout,
198
199    /// An I/O error that occurred while trying to read or write to a network stream.
200    #[display("I/O error: {}", _0)]
201    Io(io::Error),
202
203    /// Parsing a field as string failed.
204    #[display("UTF-8 error: {}", _0)]
205    Utf8(Utf8Error),
206}
207
208impl_more::impl_enum_from!(io::Error => ParseError::Io);
209impl_more::impl_enum_from!(InvalidUri => ParseError::Uri);
210impl_more::impl_enum_from!(Utf8Error => ParseError::Utf8);
211
212impl From<FromUtf8Error> for ParseError {
213    fn from(err: FromUtf8Error) -> ParseError {
214        ParseError::Utf8(err.utf8_error())
215    }
216}
217
218impl From<httparse::Error> for ParseError {
219    fn from(err: httparse::Error) -> ParseError {
220        match err {
221            httparse::Error::HeaderName
222            | httparse::Error::HeaderValue
223            | httparse::Error::NewLine
224            | httparse::Error::Token => ParseError::Header,
225            httparse::Error::Status => ParseError::Status,
226            httparse::Error::TooManyHeaders => ParseError::TooLarge,
227            httparse::Error::Version => ParseError::Version,
228        }
229    }
230}
231
232impl From<ParseError> for Error {
233    fn from(err: ParseError) -> Self {
234        Self::new_parse().with_cause(err)
235    }
236}
237
238impl From<ParseError> for Response<BoxBody> {
239    fn from(err: ParseError) -> Self {
240        Error::from(err).into()
241    }
242}
243
244/// A set of errors that can occur during payload parsing.
245#[derive(Debug, Display)]
246#[non_exhaustive]
247pub enum PayloadError {
248    /// A payload reached EOF, but is not complete.
249    #[display("Payload reached EOF before completing: {:?}", _0)]
250    Incomplete(Option<io::Error>),
251
252    /// Content encoding stream corruption.
253    #[display("Can not decode content-encoding")]
254    EncodingCorrupted,
255
256    /// Payload reached size limit.
257    #[display("Payload reached size limit")]
258    Overflow,
259
260    /// Payload length is unknown.
261    #[display("Payload length is unknown")]
262    UnknownLength,
263
264    /// HTTP/2 payload error.
265    #[cfg(feature = "http2")]
266    #[display("{}", _0)]
267    Http2Payload(::h2::Error),
268
269    /// Generic I/O error.
270    #[display("{}", _0)]
271    Io(io::Error),
272}
273
274#[cfg(feature = "http2")]
275impl_more::impl_enum_from!(::h2::Error => PayloadError::Http2Payload);
276impl_more::impl_enum_from!(Option<io::Error> => PayloadError::Incomplete);
277
278impl std::error::Error for PayloadError {
279    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
280        match self {
281            PayloadError::Incomplete(None) => None,
282            PayloadError::Incomplete(Some(err)) => Some(err),
283            PayloadError::EncodingCorrupted => None,
284            PayloadError::Overflow => None,
285            PayloadError::UnknownLength => None,
286            #[cfg(feature = "http2")]
287            PayloadError::Http2Payload(err) => Some(err),
288            PayloadError::Io(err) => Some(err),
289        }
290    }
291}
292
293impl From<io::Error> for PayloadError {
294    fn from(err: io::Error) -> Self {
295        PayloadError::Incomplete(Some(err))
296    }
297}
298
299impl From<PayloadError> for Error {
300    fn from(err: PayloadError) -> Self {
301        Self::new_payload().with_cause(err)
302    }
303}
304
305/// A set of errors that can occur during dispatching HTTP requests.
306#[derive(Debug, Display, From)]
307#[non_exhaustive]
308pub enum DispatchError {
309    /// Service error.
310    #[display("Service error")]
311    Service(Response<BoxBody>),
312
313    /// Body streaming error.
314    #[display("Body error: {}", _0)]
315    Body(Box<dyn StdError>),
316
317    /// Upgrade service error.
318    #[display("Upgrade error")]
319    Upgrade,
320
321    /// An `io::Error` that occurred while trying to read or write to a network stream.
322    #[display("I/O error: {}", _0)]
323    Io(io::Error),
324
325    /// Request parse error.
326    #[display("Request parse error: {}", _0)]
327    Parse(ParseError),
328
329    /// HTTP/2 error.
330    #[display("{}", _0)]
331    #[cfg(feature = "http2")]
332    H2(h2::Error),
333
334    /// The first request did not complete within the specified timeout.
335    #[display("Request did not complete within the specified timeout")]
336    SlowRequestTimeout,
337
338    /// Disconnect timeout. Makes sense for TLS streams.
339    #[display("Connection shutdown timeout")]
340    DisconnectTimeout,
341
342    /// Handler dropped payload before reading EOF.
343    #[display("Handler dropped payload before reading EOF")]
344    HandlerDroppedPayload,
345
346    /// Internal error.
347    #[display("Internal error")]
348    InternalError,
349}
350
351impl StdError for DispatchError {
352    fn source(&self) -> Option<&(dyn StdError + 'static)> {
353        match self {
354            DispatchError::Service(_res) => None,
355            DispatchError::Body(err) => Some(&**err),
356            DispatchError::Io(err) => Some(err),
357            DispatchError::Parse(err) => Some(err),
358
359            #[cfg(feature = "http2")]
360            DispatchError::H2(err) => Some(err),
361
362            _ => None,
363        }
364    }
365}
366
367/// A set of error that can occur during parsing content type.
368#[derive(Debug, Display, Error)]
369#[cfg_attr(test, derive(PartialEq, Eq))]
370#[non_exhaustive]
371pub enum ContentTypeError {
372    /// Can not parse content type.
373    #[display("Could not parse content type")]
374    ParseError,
375
376    /// Unknown content encoding.
377    #[display("Unknown content encoding")]
378    UnknownEncoding,
379}
380
381#[cfg(test)]
382mod tests {
383    use http::Error as HttpError;
384
385    use super::*;
386
387    #[test]
388    fn test_into_response() {
389        let resp: Response<BoxBody> = ParseError::Incomplete.into();
390        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
391
392        let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
393        let resp: Response<BoxBody> = Error::new_http().with_cause(err).into();
394        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
395    }
396
397    #[test]
398    fn test_as_response() {
399        let orig = io::Error::other("other");
400        let err: Error = ParseError::Io(orig).into();
401        assert_eq!(
402            format!("{}", err),
403            "Error parsing HTTP message: I/O error: other"
404        );
405    }
406
407    #[test]
408    fn test_error_display() {
409        let orig = io::Error::other("other");
410        let err = Error::new_io().with_cause(orig);
411        assert_eq!("Connection error: other", err.to_string());
412    }
413
414    #[test]
415    fn test_error_http_response() {
416        let orig = io::Error::other("other");
417        let err = Error::new_io().with_cause(orig);
418        let resp: Response<BoxBody> = err.into();
419        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
420    }
421
422    #[test]
423    fn test_payload_error() {
424        let err: PayloadError = io::Error::other("ParseError").into();
425        assert!(err.to_string().contains("ParseError"));
426
427        let err = PayloadError::Incomplete(None);
428        assert_eq!(
429            err.to_string(),
430            "Payload reached EOF before completing: None"
431        );
432    }
433
434    macro_rules! from {
435        ($from:expr => $error:pat) => {
436            match ParseError::from($from) {
437                err @ $error => {
438                    assert!(err.to_string().len() >= 5);
439                }
440                err => unreachable!("{:?}", err),
441            }
442        };
443    }
444
445    macro_rules! from_and_cause {
446        ($from:expr => $error:pat) => {
447            match ParseError::from($from) {
448                e @ $error => {
449                    let desc = format!("{}", e);
450                    assert_eq!(desc, format!("I/O error: {}", $from));
451                }
452                _ => unreachable!("{:?}", $from),
453            }
454        };
455    }
456
457    #[test]
458    fn test_from() {
459        from_and_cause!(io::Error::other("other") => ParseError::Io(..));
460        from!(httparse::Error::HeaderName => ParseError::Header);
461        from!(httparse::Error::HeaderName => ParseError::Header);
462        from!(httparse::Error::HeaderValue => ParseError::Header);
463        from!(httparse::Error::NewLine => ParseError::Header);
464        from!(httparse::Error::Status => ParseError::Status);
465        from!(httparse::Error::Token => ParseError::Header);
466        from!(httparse::Error::TooManyHeaders => ParseError::TooLarge);
467        from!(httparse::Error::Version => ParseError::Version);
468    }
469}