lambda_router/runtime/error.rs
1//! # error
2//! a series of different errors that can occur
3//! most handle de/serialization errors
4
5use lambda_http::ext::PayloadError;
6use serde::Serialize;
7use serde_with::{serde_as, DisplayFromStr};
8use thiserror::Error;
9
10#[serde_as]
11#[derive(Debug, Error, Serialize)]
12pub enum Error {
13 /// an error occurred when trying to serialize from a json body payload
14 #[error("{0}")]
15 SerializeJSON(
16 #[from]
17 #[serde_as(as = "DisplayFromStr")]
18 serde_json::Error,
19 ),
20
21 /// an error occurred when trying to deserialize from a url encoded query string
22 #[error("{0}")]
23 DeserializeURLEncoded(
24 #[from]
25 #[serde_as(as = "DisplayFromStr")]
26 serde_urlencoded::de::Error,
27 ),
28
29 /// an error occurred when trying to deserialize from the request body
30 #[error("{0}")]
31 Payload(#[serde_as(as = "DisplayFromStr")] PayloadError),
32
33 /// the route did not match what was expected
34 /// this variant will never bubble, because it's "caught" by the default_router which
35 /// if not provided will cause a compiler_error from the **router** macro
36 #[error("not found")]
37 NotFound,
38
39 /// the method did not match what was expected
40 #[error("method not allowed")]
41 MethodNotAllowed,
42
43 /// there was no payload sent bt all handlers are expected to get data, if you want to get no data, use the "unit" type of that data format, i.e in json this is null or use an empty struct
44 #[error("no payload")]
45 NoPayload,
46}
47
48impl Error {
49 /// checks if not found 404
50 pub fn is_not_found(&self) -> bool {
51 matches!(self, Self::NotFound)
52 }
53
54 /// convert errors to status codes
55 pub fn status_code(&self) -> u16 {
56 match self {
57 Self::NotFound => 404,
58 Self::MethodNotAllowed => 405,
59 _ => 400,
60 }
61 }
62
63 /// wraps the error in a Result<(), Error> and serializes as json
64 pub fn json(&self) -> Result<String, Self> {
65 let err: Result<(), &Self> = Err(self);
66 Ok(serde_json::to_string(&err)?)
67 }
68}