Skip to main content

ntex/http/
error.rs

1//! HTTP-related errors.
2use std::{error, fmt, io, io::Write, string::FromUtf8Error};
3
4use ntex_h2::{self as h2};
5use ntex_http::{StatusCode, header};
6
7// Re-export for convenience.
8pub use crate::channel::Canceled;
9pub use ntex_http::error::Error as HttpError;
10
11use crate::error::Failure;
12use crate::http::{body::Body, response::Response};
13use crate::util::{BytesMut, Either, clone_io_error};
14
15/// An error that can be converted into an HTTP [`Response`].
16pub trait ResponseError: error::Error {
17    /// Creates an HTTP response for this error.
18    ///
19    /// The default response has status `500 Internal Server Error`, a
20    /// `text/plain; charset=utf-8` content type, and the error's
21    /// [`Display`](fmt::Display) representation as its body. Implementations
22    /// should override this method when that text is not suitable for clients.
23    fn error_response(&self) -> Response {
24        let mut resp = Response::new(StatusCode::INTERNAL_SERVER_ERROR);
25        let mut buf = BytesMut::new();
26        let _ = write!(&mut buf, "{self}");
27        resp.headers_mut().insert(
28            header::CONTENT_TYPE,
29            header::HeaderValue::from_static("text/plain; charset=utf-8"),
30        );
31        resp.set_body(Body::from(buf))
32    }
33}
34
35impl<T: ResponseError> ResponseError for &T {
36    fn error_response(&self) -> Response {
37        (*self).error_response()
38    }
39}
40
41impl<T: ResponseError> From<T> for Response {
42    fn from(err: T) -> Response {
43        let resp = err.error_response();
44        if resp.head().status == StatusCode::INTERNAL_SERVER_ERROR {
45            log::error!("Internal Server Error: {err:?}");
46        } else {
47            log::debug!("Error in response: {err:?}");
48        }
49        resp
50    }
51}
52
53/// Return `InternalServerError` for `HttpError`,
54/// Response generation can return `HttpError`, so it is internal error
55impl ResponseError for HttpError {}
56
57/// Return `InternalServerError` for `io::Error`
58impl ResponseError for io::Error {}
59
60/// `InternalServerError` for `JsonError`
61impl ResponseError for serde_json::error::Error {}
62
63/// Errors that can occur while encoding HTTP streams.
64#[derive(thiserror::Error, Clone, Debug)]
65pub enum EncodeError {
66    /// An invalid `HttpVersion`, such as `HTP/1.1`
67    #[error("Unsupported HTTP version specified, {0:?}")]
68    UnsupportedVersion(super::Version),
69
70    /// The encoded stream ended before the message was complete.
71    #[error("Unexpected end of bytes stream")]
72    UnexpectedEof,
73
74    /// A streaming request body has neither chunked coding nor `Content-Length`.
75    #[error("Request body length is unknown")]
76    UnknownLength,
77}
78
79/// Errors that can occur while parsing HTTP streams.
80#[derive(thiserror::Error, Copy, Clone, Debug, PartialEq, Eq, Hash)]
81pub enum DecodeError {
82    /// An invalid `Method`, such as `GE.T`.
83    #[error("Invalid Method specified")]
84    Method,
85    /// An invalid `Uri`, such as `exam ple.domain`.
86    #[error("Uri error")]
87    Uri,
88    /// An invalid `HttpVersion`, such as `HTP/1.1`
89    #[error("Invalid HTTP version specified")]
90    Version,
91    /// An invalid `Header`.
92    #[error("Invalid Header provided")]
93    Header,
94    /// The message contains more headers than the configured limit.
95    #[error("Maximum number of headers are received")]
96    MaxHeaders,
97    /// A message head is too large to be reasonable.
98    #[error("Message head is too large")]
99    TooLarge(usize),
100    /// A request or status line exceeds the configured limit.
101    #[error("Request or status line is too long")]
102    StartLineTooLong(usize),
103    /// A request applies a transfer coding other than `chunked`.
104    #[error("Unsupported transfer coding")]
105    UnsupportedTransferCoding,
106    /// A message reached EOF, but is not complete.
107    #[error("Message is incomplete")]
108    Incomplete,
109    /// An invalid `Status`, such as `1337 ELITE`.
110    #[error("Invalid Status provided")]
111    Status,
112    /// An `InvalidInput` occurred while trying to parse incoming stream.
113    #[error("`InvalidInput` occurred while trying to parse incoming stream: {0}")]
114    InvalidInput(&'static str),
115    /// Parsing a field as string failed
116    #[error("UTF8 error")]
117    Utf8,
118}
119
120impl From<urly::InvalidUrl> for DecodeError {
121    fn from(_: urly::InvalidUrl) -> DecodeError {
122        DecodeError::Uri
123    }
124}
125
126impl From<FromUtf8Error> for DecodeError {
127    fn from(_: FromUtf8Error) -> DecodeError {
128        DecodeError::Utf8
129    }
130}
131
132impl From<httparse::Error> for DecodeError {
133    fn from(err: httparse::Error) -> DecodeError {
134        match err {
135            httparse::Error::HeaderName
136            | httparse::Error::HeaderValue
137            | httparse::Error::NewLine
138            | httparse::Error::Token => DecodeError::Header,
139            httparse::Error::Status => DecodeError::Status,
140            httparse::Error::TooManyHeaders => DecodeError::TooLarge(0),
141            httparse::Error::Version => DecodeError::Version,
142        }
143    }
144}
145
146impl From<ntex_httparse::Error> for DecodeError {
147    fn from(err: ntex_httparse::Error) -> DecodeError {
148        match err {
149            ntex_httparse::Error::HeaderName
150            | ntex_httparse::Error::HeaderValue
151            | ntex_httparse::Error::NewLine
152            | ntex_httparse::Error::Token => DecodeError::Header,
153            ntex_httparse::Error::Status => DecodeError::Status,
154            ntex_httparse::Error::TooManyHeaders => DecodeError::TooLarge(0),
155            ntex_httparse::Error::Version => DecodeError::Version,
156        }
157    }
158}
159
160#[derive(thiserror::Error, Debug)]
161/// Errors that can occur while processing a payload.
162pub enum PayloadError {
163    /// A payload reached EOF, but is not complete.
164    #[error("A payload reached EOF, but is not complete. With error: {0:?}")]
165    Incomplete(#[source] Option<io::Error>),
166    /// Content encoding stream corruption
167    #[error("Cannot decode content-encoding.")]
168    EncodingCorrupted,
169    /// A payload reached size limit.
170    #[error("A payload reached size limit.")]
171    Overflow,
172    /// A payload length is unknown.
173    #[error("A payload length is unknown.")]
174    UnknownLength,
175    /// Http2 payload error
176    #[error("")]
177    Http2Payload(
178        #[from]
179        #[source]
180        h2::StreamError,
181    ),
182    /// Decode error
183    #[error("Decode error")]
184    Decode(
185        #[from]
186        #[source]
187        DecodeError,
188    ),
189    /// Io error
190    #[error("{0}")]
191    Io(
192        #[from]
193        #[source]
194        io::Error,
195    ),
196}
197
198impl Clone for PayloadError {
199    fn clone(&self) -> PayloadError {
200        match self {
201            PayloadError::Incomplete(err) => {
202                PayloadError::Incomplete(err.as_ref().map(clone_io_error))
203            }
204            PayloadError::EncodingCorrupted => PayloadError::EncodingCorrupted,
205            PayloadError::Overflow => PayloadError::Overflow,
206            PayloadError::UnknownLength => PayloadError::UnknownLength,
207            PayloadError::Http2Payload(err) => PayloadError::Http2Payload(*err),
208            PayloadError::Decode(err) => PayloadError::Decode(*err),
209            PayloadError::Io(err) => PayloadError::Io(clone_io_error(err)),
210        }
211    }
212}
213
214impl From<Either<PayloadError, io::Error>> for PayloadError {
215    fn from(err: Either<PayloadError, io::Error>) -> Self {
216        match err {
217            Either::Left(err) => err,
218            Either::Right(err) => PayloadError::Io(err),
219        }
220    }
221}
222
223#[derive(thiserror::Error, Clone, Debug)]
224/// Errors that can occur while dispatching HTTP requests.
225pub enum DispatchError {
226    /// Service error
227    #[error("Service error {0}")]
228    Service(Failure),
229
230    /// Control service error
231    #[error("Control service error")]
232    Control(Failure),
233}
234
235#[derive(thiserror::Error, Clone, Debug)]
236/// Errors that can occur while dispatching HTTP/2 requests.
237pub enum H2Error {
238    /// Readiness error
239    #[error("Readiness error")]
240    Ready,
241    /// Too many consecutive empty non-final `DATA` frames
242    #[error("Too many consecutive empty DATA frames")]
243    EmptyDataFrames,
244}
245
246impl crate::error::ErrorDiagnostic for H2Error {
247    fn signature(&self) -> &'static str {
248        "ntex-http-h2error"
249    }
250}
251
252/// Errors that can occur while parsing a `Content-Type` header.
253#[derive(thiserror::Error, Copy, Clone, PartialEq, Eq, Hash, Debug)]
254pub enum ContentTypeError {
255    /// Cannot parse content type
256    #[error("Cannot parse content type")]
257    ParseError,
258    /// Unknown content encoding
259    #[error("Unknown content encoding")]
260    UnknownEncoding,
261    /// Unexpected Content-Type
262    #[error("Unexpected Content-Type")]
263    Unexpected,
264    /// Content-Type is expected
265    #[error("Content-Type is expected")]
266    Expected,
267}
268
269/// An error produced by a blocking operation.
270#[derive(thiserror::Error, Debug)]
271pub enum BlockingError<E: fmt::Debug> {
272    /// The blocking operation returned an error.
273    #[error("{0:?}")]
274    Error(#[source] E),
275    /// The thread pool stopped before completing the operation.
276    #[error("Thread pool is gone")]
277    Canceled,
278}
279
280impl From<crate::rt::JoinError> for PayloadError {
281    fn from(_: crate::rt::JoinError) -> Self {
282        PayloadError::Io(io::Error::new(
283            io::ErrorKind::Interrupted,
284            "Operation is canceled",
285        ))
286    }
287}
288
289impl From<crate::rt::BlockingError> for PayloadError {
290    fn from(_: crate::rt::BlockingError) -> Self {
291        PayloadError::Io(io::Error::new(
292            io::ErrorKind::Interrupted,
293            "Operation is canceled",
294        ))
295    }
296}
297
298impl From<BlockingError<io::Error>> for PayloadError {
299    fn from(err: BlockingError<io::Error>) -> Self {
300        match err {
301            BlockingError::Error(e) => PayloadError::Io(e),
302            BlockingError::Canceled => PayloadError::Io(io::Error::new(
303                io::ErrorKind::Interrupted,
304                "Operation is canceled",
305            )),
306        }
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use ntex_http::Error as HttpError;
314
315    #[test]
316    fn test_into_response() {
317        let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
318        let resp: Response = err.error_response();
319        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
320    }
321
322    #[test]
323    fn test_error_http_response() {
324        let orig = io::Error::other("other");
325        let resp: Response = orig.into();
326        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
327    }
328
329    #[test]
330    fn test_payload_error() {
331        let err: PayloadError = io::Error::other("DecodeError").into();
332        assert!(format!("{err}").contains("DecodeError"), "{err}");
333
334        let err: PayloadError = BlockingError::Canceled.into();
335        assert!(format!("{err}").contains("Operation is canceled"), "{err}");
336
337        let err: PayloadError = BlockingError::Error(io::Error::other("DecodeError")).into();
338        assert!(format!("{err}").contains("DecodeError"), "{err}");
339
340        let err = PayloadError::Incomplete(None);
341        assert_eq!(
342            format!("{err}"),
343            "A payload reached EOF, but is not complete. With error: None"
344        );
345    }
346
347    macro_rules! from {
348        ($from:expr => $error:pat) => {
349            match DecodeError::from($from) {
350                e @ $error => {
351                    assert!(format!("{e}").len() >= 5);
352                }
353                e => unreachable!("{e:?}"),
354            }
355        };
356    }
357
358    #[test]
359    fn test_from() {
360        from!(httparse::Error::HeaderName => DecodeError::Header);
361        from!(httparse::Error::HeaderName => DecodeError::Header);
362        from!(httparse::Error::HeaderValue => DecodeError::Header);
363        from!(httparse::Error::NewLine => DecodeError::Header);
364        from!(httparse::Error::Status => DecodeError::Status);
365        from!(httparse::Error::Token => DecodeError::Header);
366        from!(httparse::Error::TooManyHeaders => DecodeError::TooLarge(0));
367        from!(httparse::Error::Version => DecodeError::Version);
368        from!(ntex_httparse::Error::HeaderName => DecodeError::Header);
369        from!(ntex_httparse::Error::HeaderName => DecodeError::Header);
370        from!(ntex_httparse::Error::HeaderValue => DecodeError::Header);
371        from!(ntex_httparse::Error::NewLine => DecodeError::Header);
372        from!(ntex_httparse::Error::Status => DecodeError::Status);
373        from!(ntex_httparse::Error::Token => DecodeError::Header);
374        from!(ntex_httparse::Error::TooManyHeaders => DecodeError::TooLarge(0));
375        from!(ntex_httparse::Error::Version => DecodeError::Version);
376    }
377
378    #[test]
379    fn test_decode_error_from() {
380        let err = "".parse::<urly::Url>().unwrap_err();
381        assert!(matches!(DecodeError::from(err), DecodeError::Uri));
382        let err = String::from_utf8(vec![0xff]).unwrap_err();
383        assert!(matches!(DecodeError::from(err), DecodeError::Utf8));
384    }
385
386    #[test]
387    fn test_payload_error_clone() {
388        let errs = [
389            PayloadError::Incomplete(None),
390            PayloadError::Incomplete(Some(io::Error::other("inc"))),
391            PayloadError::EncodingCorrupted,
392            PayloadError::Overflow,
393            PayloadError::UnknownLength,
394            PayloadError::Http2Payload(ntex_h2::StreamError::Closed),
395            PayloadError::Decode(DecodeError::Method),
396            PayloadError::Io(io::Error::other("io")),
397        ];
398        for err in &errs {
399            assert_eq!(err.to_string(), err.clone().to_string());
400        }
401    }
402
403    #[test]
404    fn test_payload_error_conversions() {
405        let err = PayloadError::from(Either::<PayloadError, io::Error>::Left(
406            PayloadError::Overflow,
407        ));
408        assert!(matches!(err, PayloadError::Overflow));
409        let err = PayloadError::from(Either::<PayloadError, io::Error>::Right(io::Error::other(
410            "right",
411        )));
412        assert!(matches!(err, PayloadError::Io(ref e) if e.to_string() == "right"));
413
414        for err in [
415            PayloadError::from(crate::rt::JoinError),
416            PayloadError::from(crate::rt::BlockingError),
417        ] {
418            assert!(
419                matches!(err, PayloadError::Io(ref e) if e.kind() == io::ErrorKind::Interrupted)
420            );
421        }
422    }
423
424    #[test]
425    fn test_h2_error() {
426        use crate::error::ErrorDiagnostic;
427
428        let err = H2Error::EmptyDataFrames;
429        assert_eq!(err.signature(), "ntex-http-h2error");
430        assert_eq!(err.to_string(), "Too many consecutive empty DATA frames");
431    }
432}