Skip to content

Commit e66e201

Browse files
authored
Merge pull request #16 from salvo-rs/batter_error_handle
update better erroe handle
2 parents 1d486e0 + 7cb2f58 commit e66e201

File tree

2 files changed

+87
-48
lines changed

2 files changed

+87
-48
lines changed

src/template/src/app_response.hbs

Lines changed: 66 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
use salvo::{
2-
async_trait,
3-
prelude::EndpointOutRegister,
4-
writing::Json,
5-
Depot, Request, Response, Writer, hyper::StatusCode,
2+
async_trait, hyper::StatusCode, prelude::EndpointOutRegister, writing::Json, Depot, Request,
3+
Response, Writer,
64
};
75
use serde::Serialize;
86

@@ -14,7 +12,7 @@ pub struct AppResponse<T>(pub AppResult<T>);
1412
impl<T: Serialize + Default + Send> Writer for AppResponse<T> {
1513
async fn write(self, req: &mut Request, depot: &mut Depot, res: &mut Response) {
1614
match self.0 {
17-
Ok(data) => Res::with_data(data).into_response(res),
15+
Ok(data) => ResponseBuilder::with_data(data).into_response(res),
1816
Err(e) => e.write(req, depot, res).await,
1917
}
2018
}
@@ -44,19 +42,21 @@ impl<T> From<AppError> for AppResponse<T> {
4442
}
4543

4644
#[derive(Debug, Serialize, Default)]
47-
pub struct Res<T> {
45+
pub struct ResponseBuilder<T> {
4846
pub code: i32,
4947
pub data: T,
5048
pub msg: String,
5149
}
5250

53-
#[derive(Debug, Serialize, Default)]
54-
pub struct ErrRes {
51+
#[derive(Debug, Serialize)]
52+
pub struct ErrorResponseBuilder {
5553
pub code: i32,
5654
pub msg: String,
55+
#[serde(skip)]
56+
pub source_error: AppError,
5757
}
5858

59-
impl<T: Serialize + Send + Default> Res<T> {
59+
impl<T: Serialize + Send + Default> ResponseBuilder<T> {
6060
pub fn with_data(data: T) -> Self {
6161
Self {
6262
code: 0,
@@ -74,23 +74,72 @@ impl<T: Serialize + Send + Default> Res<T> {
7474
}
7575
}
7676

77-
impl ErrRes {
78-
pub fn with_err(err: &str) -> Self {
77+
impl ErrorResponseBuilder {
78+
pub fn with_err(err: AppError) -> Self {
79+
let (code, msg) = match &err {
80+
AppError::AnyHow(e) => (500, e.to_string()),
81+
AppError::ParseError(e) => (400, e.to_string()),
82+
{{#if is_sqlx}}
83+
AppError::SqlxError(e) => (500, e.to_string()),
84+
{{/if}}
85+
{{#if is_sea_orm}}
86+
AppError::DbErr(e) => (500, e.to_string()),
87+
{{/if}}
88+
{{#if is_diesel}}
89+
AppError::DieselErr(e) => (500, e.to_string()),
90+
{{/if}}
91+
{{#if is_rbatis}}
92+
AppError::RbatisErr(e) => (500, e.to_string()),
93+
{{/if}}
94+
{{#if is_mongodb}}
95+
AppError::MongoDbErr(e) => (500, e.to_string()),
96+
AppError::MongoBsonAccessError(e) => (500, e.to_string()),
97+
AppError::MongoBsonOidError(e) => (500, e.to_string()),
98+
{{/if}}
99+
{{#if need_db_conn}}
100+
AppError::ValidationError(e) => (400, e.to_string()),
101+
{{/if}}
102+
};
79103
Self {
80-
code: 500,
81-
msg: err.to_string(),
104+
code,
105+
msg,
106+
source_error: err,
82107
}
83108
}
84109
}
85-
impl<T: Serialize + Send + Default> Res<T> {
110+
impl<T: Serialize + Send + Default> ResponseBuilder<T> {
86111
pub fn into_response(self, res: &mut Response) {
87112
res.render(Json(self));
88113
}
89114
}
90115

91-
impl ErrRes {
116+
impl ErrorResponseBuilder {
92117
pub fn into_response(self, res: &mut Response) {
93-
res.stuff(StatusCode::INTERNAL_SERVER_ERROR, Json(self));
118+
let status_code = match self.source_error {
119+
AppError::AnyHow(_) => StatusCode::INTERNAL_SERVER_ERROR,
120+
AppError::ParseError(_) => StatusCode::BAD_REQUEST,
121+
{{#if is_sqlx}}
122+
AppError::SqlxError(_) => StatusCode::INTERNAL_SERVER_ERROR,
123+
{{/if}}
124+
{{#if is_sea_orm}}
125+
AppError::DbErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
126+
{{/if}}
127+
{{#if is_diesel}}
128+
AppError::DieselErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
129+
{{/if}}
130+
{{#if is_rbatis}}
131+
AppError::RbatisErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
132+
{{/if}}
133+
{{#if is_mongodb}}
134+
AppError::MongoDbErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
135+
AppError::MongoBsonAccessError(_) => StatusCode::INTERNAL_SERVER_ERROR,
136+
AppError::MongoBsonOidError(_) => StatusCode::INTERNAL_SERVER_ERROR,
137+
{{/if}}
138+
{{#if need_db_conn}}
139+
AppError::ValidationError(_) => StatusCode::BAD_REQUEST,
140+
{{/if}}
141+
};
142+
res.stuff(status_code, Json(self));
94143
}
95144
}
96145

@@ -99,7 +148,7 @@ pub type AppResult<T> = Result<T, AppError>;
99148
#[async_trait]
100149
impl Writer for AppError {
101150
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
102-
ErrRes::with_err(&self.to_string()).into_response(res)
151+
ErrorResponseBuilder::with_err(self).into_response(res)
103152
}
104153
}
105154

src/template/src/routers/user.hbs

Lines changed: 21 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{{#if is_web_site}}
22
use crate::{
3-
app_response::{AppResponse, AppResult, ErrRes},
3+
app_response::{AppResponse, AppResult, ErrorResponseBuilder},
44
dtos::user::{
55
UserAddRequest, UserLoginRequest, UserLoginResponse, UserResponse, UserUpdateRequest,
66
},
@@ -72,7 +72,7 @@ pub async fn post_login(req: JsonBody<UserLoginRequest>, res: &mut Response) {
7272
.build();
7373
res.add_cookie(cookie);
7474
}
75-
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
75+
Err(e) => ErrorResponseBuilder::with_err(e).into_response(res),
7676
}
7777
}
7878

@@ -106,9 +106,11 @@ pub async fn get_users() -> AppResponse<Vec<UserResponse>> {
106106

107107
{{else}}
108108
use crate::{
109-
app_response::AppResult,
110-
app_response::{ErrRes, Res},
111-
dtos::user::{UserAddRequest, UserLoginRequest, UserLoginResponse, UserUpdateRequest},
109+
app_response::ErrorResponseBuilder,
110+
app_response::{AppResponse, AppResult},
111+
dtos::user::{
112+
UserAddRequest, UserLoginRequest, UserLoginResponse, UserResponse, UserUpdateRequest,
113+
},
112114
services::user,
113115
};
114116
use salvo::{
@@ -130,47 +132,35 @@ pub async fn post_login(req: JsonBody<UserLoginRequest>, res: &mut Response) {
130132
.build();
131133
res.add_cookie(cookie);
132134
}
133-
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
135+
Err(e) => ErrorResponseBuilder::with_err(e).into_response(res),
134136
}
135137
}
136138

137-
#[endpoint( tags("users"))]
138-
pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
139-
let result = user::add_user(req.0).await;
140-
match result {
141-
Ok(data) => Res::with_data(data).into_response(res),
142-
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
143-
}
139+
#[endpoint(tags("users"))]
140+
pub async fn post_add_user(new_user: JsonBody<UserAddRequest>) -> AppResponse<UserResponse> {
141+
let result = user::add_user(new_user.0).await;
142+
AppResponse(result)
144143
}
145144

146145
#[endpoint( tags("users"),
147146
parameters(
148147
("id", description = "user id"),
149148
))]
150-
pub async fn put_update_user(req: &mut Request, res: &mut Response) {
151-
let req: UserUpdateRequest = req.extract().await.unwrap();
149+
pub async fn put_update_user(req: &mut Request) -> AppResult<AppResponse<UserResponse>> {
150+
let req: UserUpdateRequest = req.extract().await?;
152151
let result = user::update_user(req).await;
153-
match result {
154-
Ok(data) => Res::with_data(data).into_response(res),
155-
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
156-
}
152+
Ok(AppResponse(result))
157153
}
158154

159-
#[endpoint( tags("users"),)]
160-
pub async fn delete_user(id: PathParam<String>, res: &mut Response) {
155+
#[endpoint(tags("users"))]
156+
pub async fn delete_user(id: PathParam<String>) -> AppResponse<()> {
161157
let result = user::delete_user(id.0).await;
162-
match result {
163-
Ok(_) => Res::with_data(()).into_response(res),
164-
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
165-
}
158+
AppResponse(result)
166159
}
167160

168-
#[endpoint( tags("users"),)]
169-
pub async fn get_users(res: &mut Response) {
161+
#[endpoint(tags("users"))]
162+
pub async fn get_users() -> AppResponse<Vec<UserResponse>> {
170163
let result = user::users().await;
171-
match result {
172-
Ok(data) => Res::with_data(data).into_response(res),
173-
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
174-
}
164+
AppResponse(result)
175165
}
176166
{{/if}}

0 commit comments

Comments
 (0)