aws_lambda_router/
error.rs1use crate::response::Response;
2use thiserror::Error;
3
4#[derive(Error, Debug)]
6pub enum RouterError {
7 #[error("Route not found: {method} {path}")]
8 RouteNotFound { method: String, path: String },
9
10 #[error("Method not allowed: {method}")]
11 MethodNotAllowed { method: String },
12
13 #[error("Bad request: {0}")]
14 BadRequest(String),
15
16 #[error("Unauthorized: {0}")]
17 Unauthorized(String),
18
19 #[error("Forbidden: {0}")]
20 Forbidden(String),
21
22 #[error("Internal server error: {0}")]
23 InternalError(String),
24
25 #[error("JSON parsing error: {0}")]
26 JsonError(#[from] serde_json::Error),
27
28 #[error("Handler error: {0}")]
29 HandlerError(#[from] anyhow::Error),
30}
31
32impl From<&str> for RouterError {
34 fn from(s: &str) -> Self {
35 RouterError::InternalError(s.to_string())
36 }
37}
38
39impl From<String> for RouterError {
41 fn from(s: String) -> Self {
42 RouterError::InternalError(s)
43 }
44}
45
46impl RouterError {
47 pub fn to_response(&self) -> Response {
49 match self {
50 RouterError::RouteNotFound { method, path } => {
51 Response::not_found(&format!("Route not found: {} {}", method, path))
52 }
53 RouterError::MethodNotAllowed { method } => {
54 Response::method_not_allowed(&format!("Method not allowed: {}", method))
55 }
56 RouterError::BadRequest(msg) => Response::bad_request(msg),
57 RouterError::Unauthorized(msg) => Response::unauthorized(msg),
58 RouterError::Forbidden(msg) => Response::forbidden(msg),
59 RouterError::InternalError(msg) => Response::internal_error(msg),
60 RouterError::JsonError(e) => Response::bad_request(&format!("Invalid JSON: {}", e)),
61 RouterError::HandlerError(e) => {
62 Response::internal_error(&format!("Handler error: {}", e))
63 }
64 }
65 }
66}
67
68pub type Result<T> = std::result::Result<T, RouterError>;