ts_webapi/
into_error_response.rs1use core::error::Error;
4
5use ts_error::{IntoReport, LogError};
6
7use crate::ErrorResponse;
8
9pub trait IntoErrorResponse<T> {
11 #[track_caller]
13 fn internal_server_error(self) -> Result<T, ErrorResponse>;
14
15 #[track_caller]
17 fn not_found(self) -> Result<T, ErrorResponse>;
18
19 #[track_caller]
21 fn unauthenticated(self) -> Result<T, ErrorResponse>;
22
23 #[track_caller]
25 fn unprocessable_entity(self) -> Result<T, ErrorResponse>;
26}
27
28impl<T, E: Error + 'static> IntoErrorResponse<T> for Result<T, E> {
29 #[track_caller]
30 fn internal_server_error(self) -> Result<T, ErrorResponse> {
31 match self.into_report().log_err() {
32 Ok(v) => Ok(v),
33 Err(_) => Err(ErrorResponse::internal_server_error()),
34 }
35 }
36
37 #[track_caller]
38 fn unprocessable_entity(self) -> Result<T, ErrorResponse> {
39 match self {
40 Ok(v) => Ok(v),
41 Err(_) => Err(ErrorResponse::unprocessable_entity()),
42 }
43 }
44
45 #[track_caller]
46 fn unauthenticated(self) -> Result<T, ErrorResponse> {
47 match self {
48 Ok(v) => Ok(v),
49 Err(_) => Err(ErrorResponse::unauthenticated()),
50 }
51 }
52
53 #[track_caller]
54 fn not_found(self) -> Result<T, ErrorResponse> {
55 match self {
56 Ok(v) => Ok(v),
57 Err(_) => Err(ErrorResponse::not_found()),
58 }
59 }
60}
61
62impl<T> IntoErrorResponse<T> for Option<T> {
63 #[track_caller]
64 fn internal_server_error(self) -> Result<T, ErrorResponse> {
65 match self.log_err() {
66 Some(v) => Ok(v),
67 None => Err(ErrorResponse::internal_server_error()),
68 }
69 }
70
71 #[track_caller]
72 fn unprocessable_entity(self) -> Result<T, ErrorResponse> {
73 match self {
74 Some(v) => Ok(v),
75 None => Err(ErrorResponse::unprocessable_entity()),
76 }
77 }
78
79 #[track_caller]
80 fn unauthenticated(self) -> Result<T, ErrorResponse> {
81 match self {
82 Some(v) => Ok(v),
83 None => Err(ErrorResponse::unauthenticated()),
84 }
85 }
86
87 #[track_caller]
88 fn not_found(self) -> Result<T, ErrorResponse> {
89 match self {
90 Some(v) => Ok(v),
91 None => Err(ErrorResponse::not_found()),
92 }
93 }
94}