1use 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)] pub(crate) fn new_io() -> Self {
55 Self::new(Kind::Io)
56 }
57
58 #[allow(unused)] pub(crate) fn new_encoder() -> Self {
60 Self::new(Kind::Encoder)
61 }
62
63 #[allow(unused)] 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 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#[derive(Debug, Display, Error)]
160#[non_exhaustive]
161pub enum ParseError {
162 #[display("Invalid method specified")]
164 Method,
165
166 #[display("URI error: {}", _0)]
168 Uri(InvalidUri),
169
170 #[display("Invalid request target")]
172 RequestTarget,
173
174 #[display("Invalid HTTP version specified")]
176 Version,
177
178 #[display("Invalid Header provided")]
180 Header,
181
182 #[display("Message head is too large")]
184 TooLarge,
185
186 #[display("Message is incomplete")]
188 Incomplete,
189
190 #[display("Invalid status provided")]
192 Status,
193
194 #[allow(dead_code)]
196 #[display("Timeout")]
197 Timeout,
198
199 #[display("I/O error: {}", _0)]
201 Io(io::Error),
202
203 #[display("UTF-8 error: {}", _0)]
205 Utf8(Utf8Error),
206}
207
208impl From<io::Error> for ParseError {
209 fn from(err: io::Error) -> ParseError {
210 ParseError::Io(err)
211 }
212}
213
214impl From<InvalidUri> for ParseError {
215 fn from(err: InvalidUri) -> ParseError {
216 ParseError::Uri(err)
217 }
218}
219
220impl From<Utf8Error> for ParseError {
221 fn from(err: Utf8Error) -> ParseError {
222 ParseError::Utf8(err)
223 }
224}
225
226impl From<FromUtf8Error> for ParseError {
227 fn from(err: FromUtf8Error) -> ParseError {
228 ParseError::Utf8(err.utf8_error())
229 }
230}
231
232impl From<httparse::Error> for ParseError {
233 fn from(err: httparse::Error) -> ParseError {
234 match err {
235 httparse::Error::HeaderName
236 | httparse::Error::HeaderValue
237 | httparse::Error::NewLine
238 | httparse::Error::Token => ParseError::Header,
239 httparse::Error::Status => ParseError::Status,
240 httparse::Error::TooManyHeaders => ParseError::TooLarge,
241 httparse::Error::Version => ParseError::Version,
242 }
243 }
244}
245
246impl From<ParseError> for Error {
247 fn from(err: ParseError) -> Self {
248 Self::new_parse().with_cause(err)
249 }
250}
251
252impl From<ParseError> for Response<BoxBody> {
253 fn from(err: ParseError) -> Self {
254 Error::from(err).into()
255 }
256}
257
258#[derive(Debug, Display)]
260#[non_exhaustive]
261pub enum PayloadError {
262 #[display("Payload reached EOF before completing: {:?}", _0)]
264 Incomplete(Option<io::Error>),
265
266 #[display("Can not decode content-encoding")]
268 EncodingCorrupted,
269
270 #[display("Payload reached size limit")]
272 Overflow,
273
274 #[display("Payload length is unknown")]
276 UnknownLength,
277
278 #[cfg(feature = "http2")]
280 #[display("{}", _0)]
281 Http2Payload(::h2::Error),
282
283 #[display("{}", _0)]
285 Io(io::Error),
286}
287
288impl std::error::Error for PayloadError {
289 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
290 match self {
291 PayloadError::Incomplete(None) => None,
292 PayloadError::Incomplete(Some(err)) => Some(err),
293 PayloadError::EncodingCorrupted => None,
294 PayloadError::Overflow => None,
295 PayloadError::UnknownLength => None,
296 #[cfg(feature = "http2")]
297 PayloadError::Http2Payload(err) => Some(err),
298 PayloadError::Io(err) => Some(err),
299 }
300 }
301}
302
303#[cfg(feature = "http2")]
304impl From<::h2::Error> for PayloadError {
305 fn from(err: ::h2::Error) -> Self {
306 PayloadError::Http2Payload(err)
307 }
308}
309
310impl From<Option<io::Error>> for PayloadError {
311 fn from(err: Option<io::Error>) -> Self {
312 PayloadError::Incomplete(err)
313 }
314}
315
316impl From<io::Error> for PayloadError {
317 fn from(err: io::Error) -> Self {
318 PayloadError::Incomplete(Some(err))
319 }
320}
321
322impl From<PayloadError> for Error {
323 fn from(err: PayloadError) -> Self {
324 Self::new_payload().with_cause(err)
325 }
326}
327
328#[derive(Debug, Display, From)]
330#[non_exhaustive]
331pub enum DispatchError {
332 #[display("Service error")]
334 Service(Response<BoxBody>),
335
336 #[display("Body error: {}", _0)]
338 Body(Box<dyn StdError>),
339
340 #[display("Upgrade error")]
342 Upgrade,
343
344 #[display("I/O error: {}", _0)]
346 Io(io::Error),
347
348 #[display("Request parse error: {}", _0)]
350 Parse(ParseError),
351
352 #[display("{}", _0)]
354 #[cfg(feature = "http2")]
355 H2(h2::Error),
356
357 #[display("Request did not complete within the specified timeout")]
359 SlowRequestTimeout,
360
361 #[display("Connection shutdown timeout")]
363 DisconnectTimeout,
364
365 #[display("Handler dropped payload before reading EOF")]
367 HandlerDroppedPayload,
368
369 #[display("Internal error")]
371 InternalError,
372}
373
374impl StdError for DispatchError {
375 fn source(&self) -> Option<&(dyn StdError + 'static)> {
376 match self {
377 DispatchError::Service(_res) => None,
378 DispatchError::Body(err) => Some(&**err),
379 DispatchError::Io(err) => Some(err),
380 DispatchError::Parse(err) => Some(err),
381
382 #[cfg(feature = "http2")]
383 DispatchError::H2(err) => Some(err),
384
385 _ => None,
386 }
387 }
388}
389
390#[derive(Debug, Display, Error)]
392#[cfg_attr(test, derive(PartialEq, Eq))]
393#[non_exhaustive]
394pub enum ContentTypeError {
395 #[display("Could not parse content type")]
397 ParseError,
398
399 #[display("Unknown content encoding")]
401 UnknownEncoding,
402}
403
404#[cfg(test)]
405mod tests {
406 use http::Error as HttpError;
407
408 use super::*;
409
410 #[test]
411 fn test_into_response() {
412 let resp: Response<BoxBody> = ParseError::Incomplete.into();
413 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
414
415 let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
416 let resp: Response<BoxBody> = Error::new_http().with_cause(err).into();
417 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
418 }
419
420 #[test]
421 fn test_as_response() {
422 let orig = io::Error::other("other");
423 let err: Error = ParseError::Io(orig).into();
424 assert_eq!(
425 format!("{}", err),
426 "Error parsing HTTP message: I/O error: other"
427 );
428 }
429
430 #[test]
431 fn test_error_display() {
432 let orig = io::Error::other("other");
433 let err = Error::new_io().with_cause(orig);
434 assert_eq!("Connection error: other", err.to_string());
435 }
436
437 #[test]
438 fn test_error_http_response() {
439 let orig = io::Error::other("other");
440 let err = Error::new_io().with_cause(orig);
441 let resp: Response<BoxBody> = err.into();
442 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
443 }
444
445 #[test]
446 fn test_payload_error() {
447 let err: PayloadError = io::Error::other("ParseError").into();
448 assert!(err.to_string().contains("ParseError"));
449
450 let err = PayloadError::Incomplete(None);
451 assert_eq!(
452 err.to_string(),
453 "Payload reached EOF before completing: None"
454 );
455 }
456
457 macro_rules! from {
458 ($from:expr => $error:pat) => {
459 match ParseError::from($from) {
460 err @ $error => {
461 assert!(err.to_string().len() >= 5);
462 }
463 err => unreachable!("{:?}", err),
464 }
465 };
466 }
467
468 macro_rules! from_and_cause {
469 ($from:expr => $error:pat) => {
470 match ParseError::from($from) {
471 e @ $error => {
472 let desc = format!("{}", e);
473 assert_eq!(desc, format!("I/O error: {}", $from));
474 }
475 _ => unreachable!("{:?}", $from),
476 }
477 };
478 }
479
480 #[test]
481 fn test_from() {
482 from_and_cause!(io::Error::other("other") => ParseError::Io(..));
483 from!(httparse::Error::HeaderName => ParseError::Header);
484 from!(httparse::Error::HeaderName => ParseError::Header);
485 from!(httparse::Error::HeaderValue => ParseError::Header);
486 from!(httparse::Error::NewLine => ParseError::Header);
487 from!(httparse::Error::Status => ParseError::Status);
488 from!(httparse::Error::Token => ParseError::Header);
489 from!(httparse::Error::TooManyHeaders => ParseError::TooLarge);
490 from!(httparse::Error::Version => ParseError::Version);
491 }
492}