Skip to main content

ntex/web/
error.rs

1//! Web error
2use std::{cell::RefCell, error::Error, fmt, io::Write};
3
4pub use crate::http::error::JsonError;
5pub use ntex_http::error::Error as HttpError;
6pub use urly::InvalidUrl as UrlParseError;
7
8use crate::http::body::Body;
9use crate::http::{StatusCode, error, header};
10use crate::util::{BytesMut, Either};
11
12pub use crate::http::error::BlockingError;
13pub use crate::web::error_default::DefaultError;
14
15use super::HttpResponse;
16
17/// Error that can be rendered to a `Response`
18#[doc(alias = "ResponseError")]
19#[diagnostic::on_unimplemented(
20    message = "`{Self}` cannot be converted into a web error response",
21    label = "does not implement `WebResponseError`",
22    note = "implement `WebResponseError<St, St::Error>` for `{Self}`, where `St` is the application state; the default `error_response()` returns 500",
23    note = "or wrap the error with a helper such as `web::error::ErrorBadRequest(err)`"
24)]
25pub trait WebResponseError<St, Err>: Error + 'static {
26    /// Generate response for error
27    ///
28    /// Internal server error is generated by default.
29    fn error_response(&self, _: &St) -> HttpResponse {
30        HttpResponse::render_with(StatusCode::INTERNAL_SERVER_ERROR, &self)
31    }
32
33    /// Convert the error into a boxed trait object.
34    ///
35    /// Used when the error is stored in a [`WebError`]. `WebError` overrides
36    /// this method to return its inner error without boxing it again.
37    fn into(self) -> Box<dyn WebResponseError<St, Err>>
38    where
39        Self: Sized,
40    {
41        Box::new(self)
42    }
43}
44
45// ========================== WebErrorImpl ====================
46
47/// Type-erased web error for the `Err` error domain.
48///
49/// Web services, middleware, and filters use `WebError` as their error type.
50/// It stores any error that implements [`WebResponseError`] for the same
51/// application state and error domain, and renders it with that
52/// implementation.
53pub struct WebError<St = (), Err = DefaultError>(pub(crate) Box<dyn WebResponseError<St, Err>>);
54
55impl<St: 'static, Err: 'static> WebError<St, Err> {
56    /// Create `WebError` from an error that can be rendered for this domain.
57    pub fn from_err<E: WebResponseError<St, Err>>(err: E) -> Self {
58        Self(err.into())
59    }
60}
61
62impl<St: 'static, Err: 'static> WebResponseError<St, Err> for WebError<St, Err> {
63    fn error_response(&self, st: &St) -> HttpResponse {
64        self.0.error_response(st)
65    }
66
67    fn into(self) -> Box<dyn WebResponseError<St, Err>> {
68        self.0
69    }
70}
71
72impl<St, Err> Error for WebError<St, Err> {
73    fn source(&self) -> Option<&(dyn Error + 'static)> {
74        self.0.source()
75    }
76}
77
78impl<St, Err> crate::http::error::ResponseError for WebError<St, Err> {
79    fn error_response(&self) -> HttpResponse {
80        HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
81    }
82}
83
84impl<St, Err> fmt::Display for WebError<St, Err> {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        write!(f, "{}", self.0)
87    }
88}
89
90impl<St, Err> fmt::Debug for WebError<St, Err> {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "web::WebError({})", self.0)
93    }
94}
95
96// ========================== Error<E> ========================
97
98impl<E, St, Err> WebResponseError<St, Err> for crate::error::Error<E>
99where
100    E: WebResponseError<St, Err> + Clone,
101{
102    fn error_response(&self, st: &St) -> HttpResponse {
103        (**self).error_response(st)
104    }
105}
106
107// ==========================
108
109impl<St, Err> WebResponseError<St, Err> for std::convert::Infallible {}
110
111impl<St, Err, A, B> WebResponseError<St, Err> for Either<A, B>
112where
113    A: WebResponseError<St, Err>,
114    B: WebResponseError<St, Err>,
115{
116    fn error_response(&self, st: &St) -> HttpResponse {
117        match self {
118            Either::Left(a) => a.error_response(st),
119            Either::Right(b) => b.error_response(st),
120        }
121    }
122}
123
124/// Errors which can occur when attempting to generate resource uri.
125#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
126#[non_exhaustive]
127pub enum UrlGenerationError {
128    /// Resource not found
129    #[error("Resource not found")]
130    ResourceNotFound,
131    /// Not all path pattern covered
132    #[error("Not all path pattern covered")]
133    NotEnoughElements,
134    /// More elements than dynamic segments of the resource path
135    #[error("Too many elements for the resource path")]
136    TooManyElements,
137    /// An element does not match the pattern of its dynamic segment
138    #[error("Element does not match its path segment pattern")]
139    InvalidElement,
140    /// URL parse error
141    #[error("{0}")]
142    ParseError(
143        #[from]
144        #[source]
145        UrlParseError,
146    ),
147}
148
149/// A set of errors that can occur during parsing urlencoded payloads
150#[derive(Debug, thiserror::Error)]
151pub enum UrlencodedError {
152    /// Cannot decode chunked transfer encoding
153    #[error("Cannot decode chunked transfer encoding")]
154    Chunked,
155    /// Payload size is bigger than allowed. (default: 16kB)
156    #[error(
157        "Urlencoded payload size is bigger ({size} bytes) than allowed (default: {limit} bytes)"
158    )]
159    Overflow {
160        /// Size of the payload, in bytes.
161        size: usize,
162        /// Configured payload size limit, in bytes.
163        limit: usize,
164    },
165    /// Payload size is unknown
166    #[error("Payload size is unknown")]
167    UnknownLength,
168    /// Content type error
169    #[error("Content type error")]
170    ContentType,
171    /// Parse error
172    #[error("Parse error")]
173    Parse,
174    /// Payload error
175    #[error("Error that occur during reading payload: {0}")]
176    Payload(
177        #[from]
178        #[source]
179        error::PayloadError,
180    ),
181}
182
183/// A set of errors that can occur during parsing json payloads
184#[derive(Debug, thiserror::Error)]
185pub enum JsonPayloadError {
186    /// Payload size is bigger than allowed. (default: 32kB)
187    #[error("Json payload size is bigger than allowed")]
188    Overflow,
189    /// Content type error
190    #[error("Content type error")]
191    ContentType,
192    /// Deserialize error
193    #[error("Json deserialize error: {0}")]
194    Deserialize(
195        #[from]
196        #[source]
197        JsonError,
198    ),
199    /// Payload error
200    #[error("Error that occur during reading payload: {0}")]
201    Payload(
202        #[from]
203        #[source]
204        error::PayloadError,
205    ),
206}
207
208impl From<serde_json::Error> for JsonPayloadError {
209    fn from(err: serde_json::Error) -> Self {
210        JsonPayloadError::Deserialize(JsonError::from(err))
211    }
212}
213
214impl From<sonic_rs::Error> for JsonPayloadError {
215    fn from(err: sonic_rs::Error) -> Self {
216        JsonPayloadError::Deserialize(JsonError::from(err))
217    }
218}
219
220/// A set of errors that can occur during parsing request paths
221#[derive(Debug, thiserror::Error)]
222pub enum PathError {
223    /// Deserialize error
224    #[error("Path deserialize error: {0}")]
225    Deserialize(
226        #[from]
227        #[source]
228        serde::de::value::Error,
229    ),
230}
231
232/// A set of errors that can occur during parsing query strings
233#[derive(Debug, thiserror::Error)]
234pub enum QueryPayloadError {
235    /// Deserialize error
236    #[error("Query deserialize error: {0}")]
237    Deserialize(
238        #[from]
239        #[source]
240        serde::de::value::Error,
241    ),
242}
243
244/// Errors that can occur while reading a request payload.
245///
246/// Returned by the `Bytes` and `String` extractors and by the `Payload` stream.
247#[derive(Debug, thiserror::Error)]
248pub enum PayloadError {
249    /// Http error.
250    #[error("{0:?}")]
251    Http(
252        #[from]
253        #[source]
254        error::HttpError,
255    ),
256    /// Error while reading the payload stream.
257    #[error("{0}")]
258    Payload(
259        #[from]
260        #[source]
261        error::PayloadError,
262    ),
263    /// Invalid content type or charset.
264    #[error("{0}")]
265    ContentType(
266        #[from]
267        #[source]
268        error::ContentTypeError,
269    ),
270    /// The body cannot be decoded with the request's charset.
271    #[error("Cannot decode body")]
272    Decoding,
273}
274
275/// Helper type that can wrap any error and generate custom response.
276///
277/// `InternalError` renders the wrapped error with a fixed status code, or with a
278/// prepared response, and implements [`WebResponseError`] for every error
279/// domain. The `Error*` helpers in this module, such as [`ErrorBadRequest`],
280/// create `InternalError` values.
281///
282/// In the following example an `io::Error` is rendered as `400 Bad Request`
283/// instead of the default `500 Internal Server Error`.
284///
285/// ```rust
286/// use ntex::http::StatusCode;
287/// use ntex::web::{self, InternalError};
288///
289/// async fn index() -> Result<&'static str, InternalError<std::io::Error>> {
290///     let err = std::io::Error::other("error");
291///     Err(InternalError::new(err, StatusCode::BAD_REQUEST))
292/// }
293///
294/// let app = web::App::default().route("/", web::get().to(index));
295/// ```
296pub struct InternalError<T> {
297    cause: T,
298    status: InternalErrorType,
299}
300
301enum InternalErrorType {
302    Status(StatusCode),
303    Response(RefCell<HttpResponse>),
304}
305
306impl<T> InternalError<T> {
307    /// Create `InternalError` instance
308    pub fn default(cause: T, status: StatusCode) -> Self {
309        InternalError {
310            cause,
311            status: InternalErrorType::Status(status),
312        }
313    }
314}
315
316impl<T> InternalError<T> {
317    /// Create `InternalError` instance
318    pub fn new(cause: T, status: StatusCode) -> Self {
319        InternalError {
320            cause,
321            status: InternalErrorType::Status(status),
322        }
323    }
324
325    /// Create `InternalError` with predefined `Response`.
326    ///
327    /// Each `error_response()` call builds a response with the status, headers,
328    /// and connection type of `response`. An empty or in-memory body is repeated
329    /// on every call. A streaming body can be sent only once: the first call
330    /// gets it and later calls get an empty body. Extensions are moved into the
331    /// first response.
332    pub fn from_response(cause: T, response: HttpResponse) -> Self {
333        InternalError {
334            cause,
335            status: InternalErrorType::Response(RefCell::new(response)),
336        }
337    }
338}
339
340impl<T> fmt::Debug for InternalError<T>
341where
342    T: fmt::Debug + 'static,
343{
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        write!(f, "web::InternalError({:?})", self.cause)
346    }
347}
348
349impl<T> fmt::Display for InternalError<T>
350where
351    T: fmt::Display + 'static,
352{
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        fmt::Display::fmt(&self.cause, f)
355    }
356}
357
358impl<T: fmt::Display + fmt::Debug + 'static> std::error::Error for InternalError<T> {}
359
360impl<St, Err, T> WebResponseError<St, Err> for InternalError<T>
361where
362    T: fmt::Debug + fmt::Display + 'static,
363{
364    fn error_response(&self, _: &St) -> HttpResponse {
365        crate::http::error::ResponseError::error_response(self)
366    }
367}
368
369impl<T> crate::http::error::ResponseError for InternalError<T>
370where
371    T: fmt::Debug + fmt::Display + 'static,
372{
373    fn error_response(&self) -> HttpResponse {
374        match self.status {
375            InternalErrorType::Status(st) => {
376                let mut res = HttpResponse::new(st);
377                let mut buf = BytesMut::new();
378                let _ = write!(&mut buf, "{self}");
379                res.headers_mut().insert(
380                    header::CONTENT_TYPE,
381                    header::HeaderValue::from_static("text/plain; charset=utf-8"),
382                );
383                res.set_body(Body::from(buf))
384            }
385            InternalErrorType::Response(ref resp) => {
386                let mut stored = resp.borrow_mut();
387                let (body, kept) = match Body::from(stored.take_body()) {
388                    Body::Bytes(b) => (Body::Bytes(b.clone()), Body::Bytes(b)),
389                    Body::Message(m) => (Body::Message(m), Body::Empty),
390                    Body::Empty => (Body::Empty, Body::Empty),
391                    Body::None => (Body::None, Body::None),
392                };
393                let res = HttpResponse::builder_from(stored.head()).body(body);
394                let old = std::mem::replace(&mut *stored, HttpResponse::new(StatusCode::OK));
395                *stored = old.set_body(kept);
396                res
397            }
398        }
399    }
400}
401
402/// Helper function that creates wrapper of any error and generate *BAD
403/// REQUEST* response.
404#[allow(non_snake_case)]
405pub fn ErrorBadRequest<T>(err: T) -> InternalError<T>
406where
407    T: fmt::Debug + fmt::Display + 'static,
408{
409    InternalError::new(err, StatusCode::BAD_REQUEST)
410}
411
412/// Helper function that creates wrapper of any error and generate
413/// *UNAUTHORIZED* response.
414#[allow(non_snake_case)]
415pub fn ErrorUnauthorized<T>(err: T) -> InternalError<T>
416where
417    T: fmt::Debug + fmt::Display + 'static,
418{
419    InternalError::new(err, StatusCode::UNAUTHORIZED)
420}
421
422/// Helper function that creates wrapper of any error and generate
423/// *`PAYMENT_REQUIRED`* response.
424#[allow(non_snake_case)]
425pub fn ErrorPaymentRequired<T>(err: T) -> InternalError<T>
426where
427    T: fmt::Debug + fmt::Display + 'static,
428{
429    InternalError::new(err, StatusCode::PAYMENT_REQUIRED)
430}
431
432/// Helper function that creates wrapper of any error and generate *FORBIDDEN*
433/// response.
434#[allow(non_snake_case)]
435pub fn ErrorForbidden<T>(err: T) -> InternalError<T>
436where
437    T: fmt::Debug + fmt::Display + 'static,
438{
439    InternalError::new(err, StatusCode::FORBIDDEN)
440}
441
442/// Helper function that creates wrapper of any error and generate *NOT FOUND*
443/// response.
444#[allow(non_snake_case)]
445pub fn ErrorNotFound<T>(err: T) -> InternalError<T>
446where
447    T: fmt::Debug + fmt::Display + 'static,
448{
449    InternalError::new(err, StatusCode::NOT_FOUND)
450}
451
452/// Helper function that creates wrapper of any error and generate *METHOD NOT
453/// ALLOWED* response.
454#[allow(non_snake_case)]
455pub fn ErrorMethodNotAllowed<T>(err: T) -> InternalError<T>
456where
457    T: fmt::Debug + fmt::Display + 'static,
458{
459    InternalError::new(err, StatusCode::METHOD_NOT_ALLOWED)
460}
461
462/// Helper function that creates wrapper of any error and generate *NOT
463/// ACCEPTABLE* response.
464#[allow(non_snake_case)]
465pub fn ErrorNotAcceptable<T>(err: T) -> InternalError<T>
466where
467    T: fmt::Debug + fmt::Display + 'static,
468{
469    InternalError::new(err, StatusCode::NOT_ACCEPTABLE)
470}
471
472/// Helper function that creates wrapper of any error and generate *PROXY
473/// AUTHENTICATION REQUIRED* response.
474#[allow(non_snake_case)]
475pub fn ErrorProxyAuthenticationRequired<T>(err: T) -> InternalError<T>
476where
477    T: fmt::Debug + fmt::Display + 'static,
478{
479    InternalError::new(err, StatusCode::PROXY_AUTHENTICATION_REQUIRED)
480}
481
482/// Helper function that creates wrapper of any error and generate *REQUEST
483/// TIMEOUT* response.
484#[allow(non_snake_case)]
485pub fn ErrorRequestTimeout<T>(err: T) -> InternalError<T>
486where
487    T: fmt::Debug + fmt::Display + 'static,
488{
489    InternalError::new(err, StatusCode::REQUEST_TIMEOUT)
490}
491
492/// Helper function that creates wrapper of any error and generate *CONFLICT*
493/// response.
494#[allow(non_snake_case)]
495pub fn ErrorConflict<T>(err: T) -> InternalError<T>
496where
497    T: fmt::Debug + fmt::Display + 'static,
498{
499    InternalError::new(err, StatusCode::CONFLICT)
500}
501
502/// Helper function that creates wrapper of any error and generate *GONE*
503/// response.
504#[allow(non_snake_case)]
505pub fn ErrorGone<T>(err: T) -> InternalError<T>
506where
507    T: fmt::Debug + fmt::Display + 'static,
508{
509    InternalError::new(err, StatusCode::GONE)
510}
511
512/// Helper function that creates wrapper of any error and generate *LENGTH
513/// REQUIRED* response.
514#[allow(non_snake_case)]
515pub fn ErrorLengthRequired<T>(err: T) -> InternalError<T>
516where
517    T: fmt::Debug + fmt::Display + 'static,
518{
519    InternalError::new(err, StatusCode::LENGTH_REQUIRED)
520}
521
522/// Helper function that creates wrapper of any error and generate
523/// *PAYLOAD TOO LARGE* response.
524#[allow(non_snake_case)]
525pub fn ErrorPayloadTooLarge<T>(err: T) -> InternalError<T>
526where
527    T: fmt::Debug + fmt::Display + 'static,
528{
529    InternalError::new(err, StatusCode::PAYLOAD_TOO_LARGE)
530}
531
532/// Helper function that creates wrapper of any error and generate
533/// *URI TOO LONG* response.
534#[allow(non_snake_case)]
535pub fn ErrorUriTooLong<T>(err: T) -> InternalError<T>
536where
537    T: fmt::Debug + fmt::Display + 'static,
538{
539    InternalError::new(err, StatusCode::URI_TOO_LONG)
540}
541
542/// Helper function that creates wrapper of any error and generate
543/// *UNSUPPORTED MEDIA TYPE* response.
544#[allow(non_snake_case)]
545pub fn ErrorUnsupportedMediaType<T>(err: T) -> InternalError<T>
546where
547    T: fmt::Debug + fmt::Display + 'static,
548{
549    InternalError::new(err, StatusCode::UNSUPPORTED_MEDIA_TYPE)
550}
551
552/// Helper function that creates wrapper of any error and generate
553/// *RANGE NOT SATISFIABLE* response.
554#[allow(non_snake_case)]
555pub fn ErrorRangeNotSatisfiable<T>(err: T) -> InternalError<T>
556where
557    T: fmt::Debug + fmt::Display + 'static,
558{
559    InternalError::new(err, StatusCode::RANGE_NOT_SATISFIABLE)
560}
561
562/// Helper function that creates wrapper of any error and generate
563/// *IM A TEAPOT* response.
564#[allow(non_snake_case)]
565pub fn ErrorImATeapot<T>(err: T) -> InternalError<T>
566where
567    T: fmt::Debug + fmt::Display + 'static,
568{
569    InternalError::new(err, StatusCode::IM_A_TEAPOT)
570}
571
572/// Helper function that creates wrapper of any error and generate
573/// *MISDIRECTED REQUEST* response.
574#[allow(non_snake_case)]
575pub fn ErrorMisdirectedRequest<T>(err: T) -> InternalError<T>
576where
577    T: fmt::Debug + fmt::Display + 'static,
578{
579    InternalError::new(err, StatusCode::MISDIRECTED_REQUEST)
580}
581
582/// Helper function that creates wrapper of any error and generate
583/// *UNPROCESSABLE ENTITY* response.
584#[allow(non_snake_case)]
585pub fn ErrorUnprocessableEntity<T>(err: T) -> InternalError<T>
586where
587    T: fmt::Debug + fmt::Display + 'static,
588{
589    InternalError::new(err, StatusCode::UNPROCESSABLE_ENTITY)
590}
591
592/// Helper function that creates wrapper of any error and generate
593/// *LOCKED* response.
594#[allow(non_snake_case)]
595pub fn ErrorLocked<T>(err: T) -> InternalError<T>
596where
597    T: fmt::Debug + fmt::Display + 'static,
598{
599    InternalError::new(err, StatusCode::LOCKED)
600}
601
602/// Helper function that creates wrapper of any error and generate
603/// *FAILED DEPENDENCY* response.
604#[allow(non_snake_case)]
605pub fn ErrorFailedDependency<T>(err: T) -> InternalError<T>
606where
607    T: fmt::Debug + fmt::Display + 'static,
608{
609    InternalError::new(err, StatusCode::FAILED_DEPENDENCY)
610}
611
612/// Helper function that creates wrapper of any error and generate
613/// *UPGRADE REQUIRED* response.
614#[allow(non_snake_case)]
615pub fn ErrorUpgradeRequired<T>(err: T) -> InternalError<T>
616where
617    T: fmt::Debug + fmt::Display + 'static,
618{
619    InternalError::new(err, StatusCode::UPGRADE_REQUIRED)
620}
621
622/// Helper function that creates wrapper of any error and generate
623/// *PRECONDITION FAILED* response.
624#[allow(non_snake_case)]
625pub fn ErrorPreconditionFailed<T>(err: T) -> InternalError<T>
626where
627    T: fmt::Debug + fmt::Display + 'static,
628{
629    InternalError::new(err, StatusCode::PRECONDITION_FAILED)
630}
631
632/// Helper function that creates wrapper of any error and generate
633/// *PRECONDITION REQUIRED* response.
634#[allow(non_snake_case)]
635pub fn ErrorPreconditionRequired<T>(err: T) -> InternalError<T>
636where
637    T: fmt::Debug + fmt::Display + 'static,
638{
639    InternalError::new(err, StatusCode::PRECONDITION_REQUIRED)
640}
641
642/// Helper function that creates wrapper of any error and generate
643/// *TOO MANY REQUESTS* response.
644#[allow(non_snake_case)]
645pub fn ErrorTooManyRequests<T>(err: T) -> InternalError<T>
646where
647    T: fmt::Debug + fmt::Display + 'static,
648{
649    InternalError::new(err, StatusCode::TOO_MANY_REQUESTS)
650}
651
652/// Helper function that creates wrapper of any error and generate
653/// *REQUEST HEADER FIELDS TOO LARGE* response.
654#[allow(non_snake_case)]
655pub fn ErrorRequestHeaderFieldsTooLarge<T>(err: T) -> InternalError<T>
656where
657    T: fmt::Debug + fmt::Display + 'static,
658{
659    InternalError::new(err, StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE)
660}
661
662/// Helper function that creates wrapper of any error and generate
663/// *UNAVAILABLE FOR LEGAL REASONS* response.
664#[allow(non_snake_case)]
665pub fn ErrorUnavailableForLegalReasons<T>(err: T) -> InternalError<T>
666where
667    T: fmt::Debug + fmt::Display + 'static,
668{
669    InternalError::new(err, StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS)
670}
671
672/// Helper function that creates wrapper of any error and generate
673/// *EXPECTATION FAILED* response.
674#[allow(non_snake_case)]
675pub fn ErrorExpectationFailed<T>(err: T) -> InternalError<T>
676where
677    T: fmt::Debug + fmt::Display + 'static,
678{
679    InternalError::new(err, StatusCode::EXPECTATION_FAILED)
680}
681
682/// Helper function that creates wrapper of any error and
683/// generate *INTERNAL SERVER ERROR* response.
684#[allow(non_snake_case)]
685pub fn ErrorInternalServerError<T>(err: T) -> InternalError<T>
686where
687    T: fmt::Debug + fmt::Display + 'static,
688{
689    InternalError::new(err, StatusCode::INTERNAL_SERVER_ERROR)
690}
691
692/// Helper function that creates wrapper of any error and
693/// generate *NOT IMPLEMENTED* response.
694#[allow(non_snake_case)]
695pub fn ErrorNotImplemented<T>(err: T) -> InternalError<T>
696where
697    T: fmt::Debug + fmt::Display + 'static,
698{
699    InternalError::new(err, StatusCode::NOT_IMPLEMENTED)
700}
701
702/// Helper function that creates wrapper of any error and
703/// generate *BAD GATEWAY* response.
704#[allow(non_snake_case)]
705pub fn ErrorBadGateway<T>(err: T) -> InternalError<T>
706where
707    T: fmt::Debug + fmt::Display + 'static,
708{
709    InternalError::new(err, StatusCode::BAD_GATEWAY)
710}
711
712/// Helper function that creates wrapper of any error and
713/// generate *SERVICE UNAVAILABLE* response.
714#[allow(non_snake_case)]
715pub fn ErrorServiceUnavailable<T>(err: T) -> InternalError<T>
716where
717    T: fmt::Debug + fmt::Display + 'static,
718{
719    InternalError::new(err, StatusCode::SERVICE_UNAVAILABLE)
720}
721
722/// Helper function that creates wrapper of any error and
723/// generate *GATEWAY TIMEOUT* response.
724#[allow(non_snake_case)]
725pub fn ErrorGatewayTimeout<T>(err: T) -> InternalError<T>
726where
727    T: fmt::Debug + fmt::Display + 'static,
728{
729    InternalError::new(err, StatusCode::GATEWAY_TIMEOUT)
730}
731
732/// Helper function that creates wrapper of any error and
733/// generate *HTTP VERSION NOT SUPPORTED* response.
734#[allow(non_snake_case)]
735pub fn ErrorHttpVersionNotSupported<T>(err: T) -> InternalError<T>
736where
737    T: fmt::Debug + fmt::Display + 'static,
738{
739    InternalError::new(err, StatusCode::HTTP_VERSION_NOT_SUPPORTED)
740}
741
742/// Helper function that creates wrapper of any error and
743/// generate *VARIANT ALSO NEGOTIATES* response.
744#[allow(non_snake_case)]
745pub fn ErrorVariantAlsoNegotiates<T>(err: T) -> InternalError<T>
746where
747    T: fmt::Debug + fmt::Display + 'static,
748{
749    InternalError::new(err, StatusCode::VARIANT_ALSO_NEGOTIATES)
750}
751
752/// Helper function that creates wrapper of any error and
753/// generate *INSUFFICIENT STORAGE* response.
754#[allow(non_snake_case)]
755pub fn ErrorInsufficientStorage<T>(err: T) -> InternalError<T>
756where
757    T: fmt::Debug + fmt::Display + 'static,
758{
759    InternalError::new(err, StatusCode::INSUFFICIENT_STORAGE)
760}
761
762/// Helper function that creates wrapper of any error and
763/// generate *LOOP DETECTED* response.
764#[allow(non_snake_case)]
765pub fn ErrorLoopDetected<T>(err: T) -> InternalError<T>
766where
767    T: fmt::Debug + fmt::Display + 'static,
768{
769    InternalError::new(err, StatusCode::LOOP_DETECTED)
770}
771
772/// Helper function that creates wrapper of any error and
773/// generate *NOT EXTENDED* response.
774#[allow(non_snake_case)]
775pub fn ErrorNotExtended<T>(err: T) -> InternalError<T>
776where
777    T: fmt::Debug + fmt::Display + 'static,
778{
779    InternalError::new(err, StatusCode::NOT_EXTENDED)
780}
781
782/// Helper function that creates wrapper of any error and
783/// generate *NETWORK AUTHENTICATION REQUIRED* response.
784#[allow(non_snake_case)]
785pub fn ErrorNetworkAuthenticationRequired<T>(err: T) -> InternalError<T>
786where
787    T: fmt::Debug + fmt::Display + 'static,
788{
789    InternalError::new(err, StatusCode::NETWORK_AUTHENTICATION_REQUIRED)
790}
791
792#[cfg(test)]
793mod tests {
794    use std::io;
795
796    use super::*;
797    use crate::client::error::{ClientError, ConnectError};
798    use crate::{http, web::WebError};
799
800    /// STATEMENT: `WebError` preserves error formatting while response traits select their own status.
801    ///
802    /// HOW:
803    /// - Wrap `UrlencodedError::UnknownLength` and assert its display and debug text.
804    /// - Assert the HTTP error trait returns 500 while the web error renderer returns 411.
805    #[test]
806    fn test_into_error() {
807        let e = WebError::<(), _>::from_err(UrlencodedError::UnknownLength);
808        let s = format!("{e}");
809        assert!(s.contains("Payload size is unknown"), "{}", s);
810        let s = format!("{e:?}");
811        assert!(s.contains("web::WebError"), "{}", s);
812
813        let res = crate::http::ResponseError::error_response(&e);
814        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
815
816        let res = WebResponseError::<(), DefaultError>::error_response(
817            &UrlencodedError::UnknownLength,
818            &(),
819        );
820        assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED);
821    }
822
823    /// STATEMENT: Timeout, client, and decoding errors map to their appropriate web response statuses.
824    ///
825    /// HOW:
826    /// - Render timeout and client connection, timeout, and send errors and assert 504, 400, or 500.
827    /// - Render content-type, query, payload, UTF-8, and enabled cookie parse failures as 400.
828    #[test]
829    fn test_other_errors() {
830        use crate::util::timeout::TimeoutError;
831
832        let err = TimeoutError::<UrlencodedError>::Timeout;
833        assert_eq!(
834            WebResponseError::<(), DefaultError>::error_response(&err, &(),).status(),
835            StatusCode::GATEWAY_TIMEOUT
836        );
837
838        let err = TimeoutError::<UrlencodedError>::Service(UrlencodedError::Chunked);
839        assert_eq!(
840            WebResponseError::<(), DefaultError>::error_response(&err, &(),).status(),
841            StatusCode::BAD_REQUEST
842        );
843
844        let resp = WebResponseError::error_response(
845            &ClientError::Connect(ConnectError::SslIsNotSupported),
846            &(),
847        );
848        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
849
850        let resp = WebResponseError::error_response(&ClientError::Timeout, &());
851        assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
852
853        let resp = WebResponseError::error_response(&ClientError::Send(io::Error::other("x")), &());
854        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
855
856        #[cfg(feature = "cookie")]
857        {
858            let resp: HttpResponse =
859                WebResponseError::error_response(&coo_kie::ParseError::EmptyName, &());
860            assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
861        }
862
863        let resp = WebResponseError::error_response(
864            &crate::http::error::ContentTypeError::ParseError,
865            &(),
866        );
867        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
868
869        let err = serde_urlencoded::from_str::<i32>("bad query").unwrap_err();
870        let resp = WebResponseError::error_response(&err, &());
871        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
872
873        let err = PayloadError::Decoding;
874        let resp = WebResponseError::error_response(&err, &());
875        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
876
877        #[allow(invalid_from_utf8)]
878        let err = std::str::from_utf8(b"\xF0").unwrap_err();
879        let resp = WebResponseError::error_response(&err, &());
880        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
881
882        let err = http::error::PayloadError::EncodingCorrupted;
883        let resp = WebResponseError::error_response(&err, &());
884        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
885    }
886
887    /// STATEMENT: `Either` delegates response rendering to the error in its active branch.
888    ///
889    /// HOW:
890    /// - Render a left client timeout and a right payload-decoding error.
891    /// - Assert `GATEWAY_TIMEOUT` and `BAD_REQUEST`, respectively.
892    #[test]
893    fn test_either_error() {
894        let err: Either<ClientError, PayloadError> = Either::Left(ClientError::Timeout);
895        let resp = WebResponseError::error_response(&err, &());
896        assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
897
898        let err: Either<ClientError, PayloadError> = Either::Right(PayloadError::Decoding);
899        let resp = WebResponseError::error_response(&err, &());
900        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
901    }
902
903    /// STATEMENT: I/O error kinds distinguish missing, forbidden, and internal-server responses.
904    ///
905    /// HOW:
906    /// - Render `NotFound`, `PermissionDenied`, and an unspecified I/O error.
907    /// - Assert statuses 404, 403, and 500, respectively.
908    #[test]
909    fn test_io_error() {
910        assert_eq!(
911            StatusCode::NOT_FOUND,
912            WebResponseError::error_response(&io::Error::new(io::ErrorKind::NotFound, ""), &(),)
913                .status(),
914        );
915        assert_eq!(
916            StatusCode::FORBIDDEN,
917            WebResponseError::error_response(
918                &io::Error::new(io::ErrorKind::PermissionDenied, ""),
919                &(),
920            )
921            .status(),
922        );
923        assert_eq!(
924            StatusCode::INTERNAL_SERVER_ERROR,
925            WebResponseError::error_response(&io::Error::other(""), &(),).status(),
926        );
927    }
928
929    /// STATEMENT: URL-encoded payload errors distinguish size, length, and content-type failures.
930    ///
931    /// HOW:
932    /// - Render `Overflow`, `UnknownLength`, and `ContentType` errors.
933    /// - Assert statuses 413, 411, and 400, respectively.
934    #[test]
935    fn test_urlencoded_error() {
936        let resp: HttpResponse =
937            WebResponseError::error_response(&UrlencodedError::Overflow { size: 0, limit: 0 }, &());
938        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
939        let resp: HttpResponse =
940            WebResponseError::error_response(&UrlencodedError::UnknownLength, &());
941        assert_eq!(resp.status(), StatusCode::LENGTH_REQUIRED);
942        let resp: HttpResponse =
943            WebResponseError::error_response(&UrlencodedError::ContentType, &());
944        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
945    }
946
947    /// STATEMENT: JSON payload overflow and content-type errors use different response statuses.
948    ///
949    /// HOW:
950    /// - Render `JsonPayloadError::Overflow` and `JsonPayloadError::ContentType`.
951    /// - Assert `PAYLOAD_TOO_LARGE` and `BAD_REQUEST`, respectively.
952    #[test]
953    fn test_json_payload_error() {
954        let resp: HttpResponse = WebResponseError::error_response(&JsonPayloadError::Overflow, &());
955        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
956        let resp: HttpResponse =
957            WebResponseError::error_response(&JsonPayloadError::ContentType, &());
958        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
959    }
960
961    /// STATEMENT: Query deserialization failures produce a bad-request response.
962    ///
963    /// HOW:
964    /// - Wrap a failed integer query parse in `QueryPayloadError::Deserialize`.
965    /// - Render it and assert `BAD_REQUEST`.
966    #[test]
967    fn test_query_payload_error() {
968        let err = QueryPayloadError::Deserialize(
969            serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
970        );
971        let resp: HttpResponse = WebResponseError::error_response(&err, &());
972        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
973    }
974
975    /// STATEMENT: Path deserialization failures produce a not-found response.
976    ///
977    /// HOW:
978    /// - Wrap a failed integer parse in `PathError::Deserialize`.
979    /// - Render it and assert `NOT_FOUND`.
980    #[test]
981    fn test_path_error() {
982        let err =
983            PathError::Deserialize(serde_urlencoded::from_str::<i32>("bad path").unwrap_err());
984        let resp: HttpResponse = WebResponseError::error_response(&err, &());
985        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
986    }
987
988    /// STATEMENT: WebSocket handshake errors report method or upgrade failures and supported versions.
989    ///
990    /// HOW:
991    /// - Render each handshake error and assert 405 for a non-GET method and 400 otherwise.
992    /// - Assert an unsupported version response advertises WebSocket version 13.
993    #[cfg(feature = "ws")]
994    #[test]
995    fn test_handshake_error() {
996        use crate::ws::error::HandshakeError;
997
998        let resp = WebResponseError::<_, DefaultError>::error_response(
999            &HandshakeError::GetMethodRequired,
1000            &(),
1001        );
1002        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
1003        let resp = WebResponseError::<_, DefaultError>::error_response(
1004            &HandshakeError::NoWebsocketUpgrade,
1005            &(),
1006        );
1007        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1008        let resp = WebResponseError::<_, DefaultError>::error_response(
1009            &HandshakeError::NoConnectionUpgrade,
1010            &(),
1011        );
1012        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1013        let resp = WebResponseError::<_, DefaultError>::error_response(
1014            &HandshakeError::NoVersionHeader,
1015            &(),
1016        );
1017        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1018        let resp = WebResponseError::<_, DefaultError>::error_response(
1019            &HandshakeError::UnsupportedVersion,
1020            &(),
1021        );
1022        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1023        assert_eq!(
1024            resp.headers().get(header::SEC_WEBSOCKET_VERSION).unwrap(),
1025            "13"
1026        );
1027        let resp = WebResponseError::<_, DefaultError>::error_response(
1028            &HandshakeError::BadWebsocketKey,
1029            &(),
1030        );
1031        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1032        let resp = WebResponseError::<_, DefaultError>::error_response(
1033            &HandshakeError::BadWebsocketProtocol,
1034            &(),
1035        );
1036        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1037    }
1038
1039    /// STATEMENT: Error helper constructors render their corresponding HTTP status codes.
1040    ///
1041    /// HOW:
1042    /// - Check `InternalError` debug identity and a custom bad-request response.
1043    /// - Render the client- and server-error helper constructors and assert every named status.
1044    #[test]
1045    fn test_error_helpers() {
1046        let err = ErrorBadRequest::<_>("err");
1047        assert!(format!("{err:?}").contains("web::InternalError"));
1048
1049        let err: InternalError<_> =
1050            InternalError::from_response("err", HttpResponse::BadRequest().build());
1051        let r = WebResponseError::<_, DefaultError>::error_response(&err, &());
1052        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
1053
1054        let r =
1055            WebResponseError::<_, DefaultError>::error_response(&ErrorBadRequest::<_>("err"), &());
1056        assert_eq!(r.status(), StatusCode::BAD_REQUEST);
1057
1058        let r = WebResponseError::<_, DefaultError>::error_response(
1059            &ErrorUnauthorized::<_>("err"),
1060            &(),
1061        );
1062        assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
1063
1064        let r = WebResponseError::<_, DefaultError>::error_response(
1065            &ErrorPaymentRequired::<_>("err"),
1066            &(),
1067        );
1068        assert_eq!(r.status(), StatusCode::PAYMENT_REQUIRED);
1069
1070        let r =
1071            WebResponseError::<_, DefaultError>::error_response(&ErrorForbidden::<_>("err"), &());
1072        assert_eq!(r.status(), StatusCode::FORBIDDEN);
1073
1074        let r =
1075            WebResponseError::<_, DefaultError>::error_response(&ErrorNotFound::<_>("err"), &());
1076        assert_eq!(r.status(), StatusCode::NOT_FOUND);
1077
1078        let r = WebResponseError::<_, DefaultError>::error_response(
1079            &ErrorMethodNotAllowed::<_>("err"),
1080            &(),
1081        );
1082        assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED);
1083
1084        let r = WebResponseError::<_, DefaultError>::error_response(
1085            &ErrorNotAcceptable::<_>("err"),
1086            &(),
1087        );
1088        assert_eq!(r.status(), StatusCode::NOT_ACCEPTABLE);
1089
1090        let r = WebResponseError::<_, DefaultError>::error_response(
1091            &ErrorProxyAuthenticationRequired::<_>("err"),
1092            &(),
1093        );
1094        assert_eq!(r.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED);
1095
1096        let r = WebResponseError::<_, DefaultError>::error_response(
1097            &ErrorRequestTimeout::<_>("err"),
1098            &(),
1099        );
1100        assert_eq!(r.status(), StatusCode::REQUEST_TIMEOUT);
1101
1102        let r =
1103            WebResponseError::<_, DefaultError>::error_response(&ErrorConflict::<_>("err"), &());
1104        assert_eq!(r.status(), StatusCode::CONFLICT);
1105
1106        let r = WebResponseError::<_, DefaultError>::error_response(&ErrorGone::<_>("err"), &());
1107        assert_eq!(r.status(), StatusCode::GONE);
1108
1109        let r = WebResponseError::<_, DefaultError>::error_response(
1110            &ErrorLengthRequired::<_>("err"),
1111            &(),
1112        );
1113        assert_eq!(r.status(), StatusCode::LENGTH_REQUIRED);
1114
1115        let r = WebResponseError::<_, DefaultError>::error_response(
1116            &ErrorPreconditionFailed::<_>("err"),
1117            &(),
1118        );
1119        assert_eq!(r.status(), StatusCode::PRECONDITION_FAILED);
1120
1121        let r = WebResponseError::<_, DefaultError>::error_response(
1122            &ErrorPayloadTooLarge::<_>("err"),
1123            &(),
1124        );
1125        assert_eq!(r.status(), StatusCode::PAYLOAD_TOO_LARGE);
1126
1127        let r =
1128            WebResponseError::<_, DefaultError>::error_response(&ErrorUriTooLong::<_>("err"), &());
1129        assert_eq!(r.status(), StatusCode::URI_TOO_LONG);
1130
1131        let r = WebResponseError::<_, DefaultError>::error_response(
1132            &ErrorUnsupportedMediaType::<_>("err"),
1133            &(),
1134        );
1135        assert_eq!(r.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
1136
1137        let r = WebResponseError::<_, DefaultError>::error_response(
1138            &ErrorRangeNotSatisfiable::<_>("err"),
1139            &(),
1140        );
1141        assert_eq!(r.status(), StatusCode::RANGE_NOT_SATISFIABLE);
1142
1143        let r = WebResponseError::<_, DefaultError>::error_response(
1144            &ErrorExpectationFailed::<_>("err"),
1145            &(),
1146        );
1147        assert_eq!(r.status(), StatusCode::EXPECTATION_FAILED);
1148
1149        let r =
1150            WebResponseError::<_, DefaultError>::error_response(&ErrorImATeapot::<_>("err"), &());
1151        assert_eq!(r.status(), StatusCode::IM_A_TEAPOT);
1152
1153        let r = WebResponseError::<_, DefaultError>::error_response(
1154            &ErrorMisdirectedRequest::<_>("err"),
1155            &(),
1156        );
1157        assert_eq!(r.status(), StatusCode::MISDIRECTED_REQUEST);
1158
1159        let r = WebResponseError::<_, DefaultError>::error_response(
1160            &ErrorUnprocessableEntity::<_>("err"),
1161            &(),
1162        );
1163        assert_eq!(r.status(), StatusCode::UNPROCESSABLE_ENTITY);
1164
1165        let r = WebResponseError::<_, DefaultError>::error_response(&ErrorLocked::<_>("err"), &());
1166        assert_eq!(r.status(), StatusCode::LOCKED);
1167
1168        let r = WebResponseError::<_, DefaultError>::error_response(
1169            &ErrorFailedDependency::<_>("err"),
1170            &(),
1171        );
1172        assert_eq!(r.status(), StatusCode::FAILED_DEPENDENCY);
1173
1174        let r = WebResponseError::<_, DefaultError>::error_response(
1175            &ErrorUpgradeRequired::<_>("err"),
1176            &(),
1177        );
1178        assert_eq!(r.status(), StatusCode::UPGRADE_REQUIRED);
1179
1180        let r = WebResponseError::<_, DefaultError>::error_response(
1181            &ErrorPreconditionRequired::<_>("err"),
1182            &(),
1183        );
1184        assert_eq!(r.status(), StatusCode::PRECONDITION_REQUIRED);
1185
1186        let r = WebResponseError::<_, DefaultError>::error_response(
1187            &ErrorTooManyRequests::<_>("err"),
1188            &(),
1189        );
1190        assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);
1191
1192        let r = WebResponseError::<_, DefaultError>::error_response(
1193            &ErrorRequestHeaderFieldsTooLarge::<_>("err"),
1194            &(),
1195        );
1196        assert_eq!(r.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE);
1197
1198        let r = WebResponseError::<_, DefaultError>::error_response(
1199            &ErrorUnavailableForLegalReasons::<_>("err"),
1200            &(),
1201        );
1202        assert_eq!(r.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS);
1203
1204        let r = WebResponseError::<_, DefaultError>::error_response(
1205            &ErrorInternalServerError::<_>("err"),
1206            &(),
1207        );
1208        assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR);
1209
1210        let r = WebResponseError::<_, DefaultError>::error_response(
1211            &ErrorNotImplemented::<_>("err"),
1212            &(),
1213        );
1214        assert_eq!(r.status(), StatusCode::NOT_IMPLEMENTED);
1215
1216        let r =
1217            WebResponseError::<_, DefaultError>::error_response(&ErrorBadGateway::<_>("err"), &());
1218        assert_eq!(r.status(), StatusCode::BAD_GATEWAY);
1219
1220        let r = WebResponseError::<_, DefaultError>::error_response(
1221            &ErrorServiceUnavailable::<_>("err"),
1222            &(),
1223        );
1224        assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
1225
1226        let r = WebResponseError::<_, DefaultError>::error_response(
1227            &ErrorGatewayTimeout::<_>("err"),
1228            &(),
1229        );
1230        assert_eq!(r.status(), StatusCode::GATEWAY_TIMEOUT);
1231
1232        let r = WebResponseError::<_, DefaultError>::error_response(
1233            &ErrorHttpVersionNotSupported::<_>("err"),
1234            &(),
1235        );
1236        assert_eq!(r.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED);
1237
1238        let r = WebResponseError::<_, DefaultError>::error_response(
1239            &ErrorVariantAlsoNegotiates::<_>("err"),
1240            &(),
1241        );
1242        assert_eq!(r.status(), StatusCode::VARIANT_ALSO_NEGOTIATES);
1243
1244        let r = WebResponseError::<_, DefaultError>::error_response(
1245            &ErrorInsufficientStorage::<_>("err"),
1246            &(),
1247        );
1248        assert_eq!(r.status(), StatusCode::INSUFFICIENT_STORAGE);
1249
1250        let r = WebResponseError::<_, DefaultError>::error_response(
1251            &ErrorLoopDetected::<_>("err"),
1252            &(),
1253        );
1254        assert_eq!(r.status(), StatusCode::LOOP_DETECTED);
1255
1256        let r =
1257            WebResponseError::<_, DefaultError>::error_response(&ErrorNotExtended::<_>("err"), &());
1258        assert_eq!(r.status(), StatusCode::NOT_EXTENDED);
1259
1260        let r = WebResponseError::<_, DefaultError>::error_response(
1261            &ErrorNetworkAuthenticationRequired::<_>("err"),
1262            &(),
1263        );
1264        assert_eq!(r.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED);
1265    }
1266
1267    /// STATEMENT: Default renderers classify serialization, cancellation, and payload failures.
1268    ///
1269    /// HOW:
1270    /// - Render `JsonError`, `serde_json::Error`, `sonic_rs::Error`, URL-encoding, header,
1271    ///   URL-generation, and cancellation errors as 500.
1272    /// - Assert generic deserialization and client-payload failures return 400, overflow returns 413,
1273    ///   and an enabled OpenSSL error returns 400.
1274    #[test]
1275    fn test_default_error_renderers() {
1276        use serde::de::Error as _;
1277
1278        fn status<E: WebResponseError<(), DefaultError>>(err: &E) -> StatusCode {
1279            WebResponseError::<(), DefaultError>::error_response(err, &()).status()
1280        }
1281
1282        let err = serde_json::from_str::<i32>("x").unwrap_err();
1283        assert_eq!(status(&err), StatusCode::INTERNAL_SERVER_ERROR);
1284        assert_eq!(
1285            status(&JsonError::from(err)),
1286            StatusCode::INTERNAL_SERVER_ERROR
1287        );
1288        let err = sonic_rs::from_str::<i32>("x").unwrap_err();
1289        assert_eq!(status(&err), StatusCode::INTERNAL_SERVER_ERROR);
1290        let err = serde_urlencoded::to_string(1).unwrap_err();
1291        assert_eq!(status(&err), StatusCode::INTERNAL_SERVER_ERROR);
1292        let err = serde::de::value::Error::custom("bad");
1293        assert_eq!(status(&err), StatusCode::BAD_REQUEST);
1294        assert_eq!(
1295            status(&crate::http::error::Canceled),
1296            StatusCode::INTERNAL_SERVER_ERROR
1297        );
1298        assert_eq!(
1299            status(&BlockingError::<io::Error>::Canceled),
1300            StatusCode::INTERNAL_SERVER_ERROR
1301        );
1302        let err: HttpError = http::header::HeaderName::try_from("bad header")
1303            .unwrap_err()
1304            .into();
1305        assert_eq!(status(&err), StatusCode::INTERNAL_SERVER_ERROR);
1306        assert_eq!(
1307            status(&UrlGenerationError::ResourceNotFound),
1308            StatusCode::INTERNAL_SERVER_ERROR
1309        );
1310        assert_eq!(
1311            status(&crate::client::error::ClientPayloadError(
1312                http::error::PayloadError::Incomplete(None)
1313            )),
1314            StatusCode::BAD_REQUEST
1315        );
1316        assert_eq!(
1317            status(&http::error::PayloadError::Overflow),
1318            StatusCode::PAYLOAD_TOO_LARGE
1319        );
1320
1321        #[cfg(feature = "openssl")]
1322        {
1323            let err = tls_openssl::ssl::Error::from(tls_openssl::error::ErrorStack::get());
1324            assert_eq!(status(&err), StatusCode::BAD_REQUEST);
1325        }
1326    }
1327
1328    #[derive(Debug, thiserror::Error)]
1329    #[error("custom error")]
1330    struct CustomError(#[source] io::Error);
1331
1332    impl WebResponseError<(), DefaultError> for CustomError {}
1333
1334    /// STATEMENT: `WebError` preserves sources and display text across wrapping and renders defaults.
1335    ///
1336    /// HOW:
1337    /// - Render a custom error directly and wrapped, checking 500 and its inner source text.
1338    /// - Wrap the `WebError` again and assert the original display text and status remain intact.
1339    /// - Render a generic cancellation error and assert 500.
1340    #[test]
1341    fn test_web_error() {
1342        let err = CustomError(io::Error::other("inner"));
1343        let res = WebResponseError::<(), DefaultError>::error_response(&err, &());
1344        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
1345
1346        let err = WebError::<(), DefaultError>::from_err(CustomError(io::Error::other("inner")));
1347        assert_eq!(err.source().unwrap().to_string(), "inner");
1348        let res = WebResponseError::error_response(&err, &());
1349        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
1350
1351        // WebError is not boxed twice
1352        let err = WebError::<(), DefaultError>::from_err(err);
1353        assert_eq!(err.to_string(), "custom error");
1354        let res = WebResponseError::error_response(&err, &());
1355        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
1356
1357        let err = crate::error::Error::from(crate::http::error::Canceled);
1358        let res = WebResponseError::<(), DefaultError>::error_response(&err, &());
1359        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
1360    }
1361
1362    /// STATEMENT: An `InternalError` built from a response renders the same response on
1363    /// every call; a streaming body is sent only once.
1364    ///
1365    /// HOW:
1366    /// - Build the error from a `409` response with an `x-test` header, a forced close,
1367    ///   a `u32` extension, and body `conflict`, then render it twice.
1368    /// - Confirm both renders keep status, header, connection type, and body, and only
1369    ///   the first carries the extension.
1370    /// - Build an error from a `502` streaming response, render it twice, and confirm the
1371    ///   first render has the stream and the second keeps the status with an empty body.
1372    #[test]
1373    fn test_internal_error_response_reuse() {
1374        use crate::http::{ConnectionType, body::BodySize, body::MessageBody, body::ResponseBody};
1375
1376        let res = HttpResponse::Conflict()
1377            .header("x-test", "1")
1378            .force_close()
1379            .body("conflict");
1380        res.extensions_mut().insert(7u32);
1381        let err = InternalError::from_response("err", res);
1382        for ext in [Some(7u32), None] {
1383            let res = WebResponseError::<(), DefaultError>::error_response(&err, &());
1384            assert_eq!(res.status(), StatusCode::CONFLICT);
1385            assert_eq!(res.headers().get("x-test").unwrap(), "1");
1386            assert_eq!(res.head().connection_type(), ConnectionType::Close);
1387            assert_eq!(res.extensions().get::<u32>().copied(), ext);
1388            assert!(matches!(
1389                res.body(),
1390                ResponseBody::Other(Body::Bytes(b)) | ResponseBody::Body(Body::Bytes(b))
1391                    if b == &b"conflict"[..]
1392            ));
1393        }
1394
1395        let stream =
1396            futures_util::stream::iter([Ok::<_, io::Error>(crate::util::Bytes::from_static(b"x"))]);
1397        let err = InternalError::from_response("err", HttpResponse::BadGateway().streaming(stream));
1398        let res = WebResponseError::<(), DefaultError>::error_response(&err, &());
1399        assert_eq!(res.status(), StatusCode::BAD_GATEWAY);
1400        assert_eq!(res.body().size(), BodySize::Stream);
1401        let res = WebResponseError::<(), DefaultError>::error_response(&err, &());
1402        assert_eq!(res.status(), StatusCode::BAD_GATEWAY);
1403        assert_eq!(res.body().size(), BodySize::Empty);
1404    }
1405}