ts_webapi/
into_error_response.rs

1//! Trait for providing convenience functions to mark an error as a given type.
2
3use core::error::Error;
4
5use ts_error::{IntoReport, LogError};
6
7use crate::error_response::ErrorResponse;
8
9/// Trait for providing convenience functions to mark an error as a given type.
10pub trait IntoErrorResponse<T> {
11    /// Mark the error as an internal server error.
12    #[track_caller]
13    fn internal_server_error(self) -> Result<T, ErrorResponse>;
14
15    /// Mark the error as caused because the resource could not be found.
16    #[track_caller]
17    fn not_found(self) -> Result<T, ErrorResponse>;
18}
19
20impl<T, E: Error + 'static> IntoErrorResponse<T> for Result<T, E> {
21    #[track_caller]
22    fn internal_server_error(self) -> Result<T, ErrorResponse> {
23        match self.into_report().log_err() {
24            Ok(v) => Ok(v),
25            Err(_) => Err(ErrorResponse::InternalServerError),
26        }
27    }
28
29    #[track_caller]
30    fn not_found(self) -> Result<T, ErrorResponse> {
31        match self {
32            Ok(v) => Ok(v),
33            Err(_) => Err(ErrorResponse::NotFound),
34        }
35    }
36}
37
38impl<T> IntoErrorResponse<T> for Option<T> {
39    #[track_caller]
40    fn internal_server_error(self) -> Result<T, ErrorResponse> {
41        match self.log_err() {
42            Some(v) => Ok(v),
43            None => Err(ErrorResponse::InternalServerError),
44        }
45    }
46
47    #[track_caller]
48    fn not_found(self) -> Result<T, ErrorResponse> {
49        match self {
50            Some(v) => Ok(v),
51            None => Err(ErrorResponse::NotFound),
52        }
53    }
54}