Skip to content

Commit 8e5cdda

Browse files
Merge pull request #58 from hubertshelley/features/2.0/refactor_exception_handler
refactor: exception_handler重构
2 parents e444345 + 6ba8997 commit 8e5cdda

File tree

7 files changed

+53
-113
lines changed

7 files changed

+53
-113
lines changed
Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use serde::{Deserialize, Serialize};
2+
3+
use silent::middlewares::ExceptionHandler;
24
use silent::prelude::*;
35

46
#[derive(Deserialize, Serialize, Debug)]
@@ -10,13 +12,8 @@ struct Exception {
1012
fn main() {
1113
logger::fmt().with_max_level(Level::INFO).init();
1214
let route = Route::new("")
15+
.root_hook(ExceptionHandler::new(|res, _| async move { res }))
1316
.get(|mut req| async move { req.params_parse::<Exception>() })
14-
.route()
15-
.set_exception_handler(|e, _| async move {
16-
Exception {
17-
code: e.status().as_u16(),
18-
msg: e.to_string(),
19-
}
20-
});
17+
.route();
2118
Server::new().run(route);
2219
}

silent/src/error/exception_handler_trait.rs

Lines changed: 0 additions & 7 deletions
This file was deleted.

silent/src/error/exception_handler_wrapper.rs

Lines changed: 0 additions & 75 deletions
This file was deleted.

silent/src/error/mod.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
1-
mod exception_handler_trait;
2-
mod exception_handler_wrapper;
3-
41
use crate::headers::ContentType;
52
use crate::{Response, StatusCode};
6-
pub(crate) use exception_handler_trait::ExceptionHandler;
7-
pub(crate) use exception_handler_wrapper::ExceptionHandlerWrapper;
83
use serde::Serialize;
94
use serde_json::Value;
105
use std::backtrace::Backtrace;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
use std::future::Future;
2+
use std::sync::Arc;
3+
4+
use async_trait::async_trait;
5+
6+
use crate::middleware::middleware_trait::Next;
7+
use crate::{Configs, MiddleWareHandler, Request, Response, Result};
8+
9+
/// ExceptionHandler 中间件
10+
/// ```rust
11+
/// use silent::prelude::*;
12+
/// use silent::middlewares::{ExceptionHandler};
13+
/// // Define a custom error handler function
14+
/// let _ = ExceptionHandler::new(|res, _configs| async {res});
15+
#[derive(Default, Clone)]
16+
pub struct ExceptionHandler<F> {
17+
handler: Arc<F>,
18+
}
19+
20+
impl<F, Fut, T> ExceptionHandler<F>
21+
where
22+
Fut: Future<Output = Result<T>> + Send + 'static,
23+
F: Fn(Result<Response>, Configs) -> Fut + Send + Sync + 'static,
24+
T: Into<Response>,
25+
{
26+
pub fn new(handler: F) -> Self {
27+
Self {
28+
handler: Arc::new(handler),
29+
}
30+
}
31+
}
32+
33+
#[async_trait]
34+
impl<F, Fut, T> MiddleWareHandler for ExceptionHandler<F>
35+
where
36+
Fut: Future<Output = Result<T>> + Send + 'static,
37+
F: Fn(Result<Response>, Configs) -> Fut + Send + Sync + 'static,
38+
T: Into<Response>,
39+
{
40+
async fn handle(&self, req: Request, next: &Next) -> Result<Response> {
41+
let configs = req.configs();
42+
self.handler.clone()(next.call(req).await, configs)
43+
.await
44+
.map(|r| r.into())
45+
}
46+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
mod cors;
2+
mod exception_handler;
23

34
pub use cors::{Cors, CorsType};
5+
pub use exception_handler::ExceptionHandler;

silent/src/route/root.rs

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::error::{ExceptionHandler, ExceptionHandlerWrapper};
21
#[cfg(feature = "grpc")]
32
use crate::grpc::GrpcHandler;
43
use crate::middleware::middleware_trait::Next;
@@ -20,7 +19,6 @@ use chrono::Utc;
2019
#[cfg(feature = "grpc")]
2120
use http::Method;
2221
use std::fmt;
23-
use std::future::Future;
2422
use std::sync::Arc;
2523
#[cfg(feature = "scheduler")]
2624
use tokio::sync::Mutex;
@@ -35,7 +33,6 @@ use tonic::server::NamedService;
3533
pub struct RootRoute {
3634
pub(crate) children: Vec<Route>,
3735
pub(crate) middlewares: Vec<Arc<dyn MiddleWareHandler>>,
38-
pub(crate) exception_handler: Option<Arc<dyn ExceptionHandler>>,
3936
#[cfg(feature = "session")]
4037
pub(crate) session_set: bool,
4138
pub(crate) configs: Option<Configs>,
@@ -60,7 +57,6 @@ impl RootRoute {
6057
Self {
6158
children: vec![],
6259
middlewares: vec![],
63-
exception_handler: None,
6460
#[cfg(feature = "session")]
6561
session_set: false,
6662
configs: None,
@@ -121,16 +117,6 @@ impl RootRoute {
121117
.iter_mut()
122118
.for_each(|r| r.middleware_hook_first(handler.clone()));
123119
}
124-
125-
pub fn set_exception_handler<F, T, Fut>(mut self, handler: F) -> Self
126-
where
127-
Fut: Future<Output = T> + Send + 'static,
128-
F: Fn(SilentError, Configs) -> Fut + Send + Sync + 'static,
129-
T: Into<Response>,
130-
{
131-
self.exception_handler = Some(ExceptionHandlerWrapper::new(handler).arc());
132-
self
133-
}
134120
pub(crate) fn set_configs(&mut self, configs: Option<Configs>) {
135121
self.configs = configs;
136122
}
@@ -140,7 +126,6 @@ impl RootRoute {
140126
impl Handler for RootRoute {
141127
async fn call(&self, mut req: Request) -> Result<Response, SilentError> {
142128
tracing::debug!("{:?}", req);
143-
let exception_handler = self.exception_handler.clone();
144129
let configs = self.configs.clone().unwrap_or_default();
145130
req.configs = configs.clone();
146131
let method = req.method().clone();
@@ -193,10 +178,7 @@ impl Handler for RootRoute {
193178
req_time.num_nanoseconds().unwrap_or(0) as f64 / 1000000.0,
194179
e.to_string()
195180
);
196-
match exception_handler {
197-
Some(handler) => handler.call(e, configs.clone()).await,
198-
None => e.into(),
199-
}
181+
e.into()
200182
}
201183
})
202184
}

0 commit comments

Comments
 (0)