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