actix_web_error/
lib.rs

1//! Error responses for actix-web made easy.
2//! <!-- We don't depend on `actix_web` -->
3//! This crate will make it easy implementing [`actix_web::ResponseError`](https://docs.rs/actix-web/latest/actix_web/trait.ResponseError.html) for errors.
4//! It's best used in combination with [thiserror](https://docs.rs/thiserror).
5//!
6//! # Error Responses
7//!
8//! * [`Json`] will respond with JSON in the form of `{ "error": <`[`Display`](std::fmt::Display)` representation> }` (`application/json`).
9//! * [`Text`] will respond with the [`Display`](std::fmt::Display) representation of the error (`text/plain`).
10//!
11//! # Example
12//!
13//! ```
14//! #[derive(Debug, thiserror::Error, actix_web_error::Json)]
15//! #[status(BAD_REQUEST)] // default status for all variants
16//! enum MyError {
17//!     #[error("Missing: {0}")]
18//!     MissingField(&'static str),
19//!     #[error("Malformed Date")]
20//!     MalformedDate,
21//!     #[error("Internal Server Error")]
22//!     #[status(500)] // specific override
23//!     Internal,
24//! }
25//!
26//! #[derive(Debug, thiserror::Error, actix_web_error::Text)]
27//! #[error("Item not found")]
28//! #[status(404)]
29//! struct MyOtherError;
30//! # fn main() {}
31//! ```
32//!
33#![warn(clippy::cargo)]
34#![warn(clippy::pedantic)]
35
36pub use actix_web_error_derive::*;
37
38#[doc(hidden)]
39pub mod __private {
40    use serde::{ser::SerializeStruct, Serialize, Serializer};
41    use std::fmt::Display;
42
43    #[repr(transparent)]
44    pub struct JsonErrorSerialize<'a, T>(pub &'a T);
45
46    impl<'a, T> Serialize for JsonErrorSerialize<'a, T>
47    where
48        T: Display,
49    {
50        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
51        where
52            S: Serializer,
53        {
54            let mut ser = serializer.serialize_struct("_", 1)?;
55            ser.serialize_field("error", &self.0.to_string())?;
56            ser.end()
57        }
58    }
59}