1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-10 19:01:05 +00:00
actix-web/src/middleware/err_handlers.rs

243 lines
7.3 KiB
Rust
Raw Normal View History

//! For middleware documentation, see [`ErrorHandlers`].
use std::{
future::Future,
pin::Pin,
rc::Rc,
task::{Context, Poll},
};
use actix_service::{Service, Transform};
2021-01-04 04:29:07 +00:00
use ahash::AHashMap;
use futures_core::{future::LocalBoxFuture, ready};
use pin_project_lite::pin_project;
use crate::{
dev::{ServiceRequest, ServiceResponse},
http::StatusCode,
2021-06-17 16:57:58 +00:00
Error, Result,
};
/// Return type for [`ErrorHandlers`] custom handlers.
pub enum ErrorHandlerResponse<B> {
/// Immediate HTTP response.
Response(ServiceResponse<B>),
/// A future that resolves to an HTTP response.
2019-11-21 08:52:33 +00:00
Future(LocalBoxFuture<'static, Result<ServiceResponse<B>, Error>>),
}
2019-07-17 09:48:37 +00:00
type ErrorHandler<B> = dyn Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>;
/// Middleware for registering custom status code based error handlers.
///
/// Register handlers with the `ErrorHandlers::handler()` method to register a custom error handler
/// for a given status code. Handlers can modify existing responses or create completely new ones.
///
2021-02-10 12:10:03 +00:00
/// # Examples
/// ```
/// use actix_web::middleware::{ErrorHandlers, ErrorHandlerResponse};
/// use actix_web::{web, dev, App, HttpRequest, HttpResponse, Result};
/// use actix_web::http::{StatusCode, header};
///
/// fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
/// res.response_mut()
/// .headers_mut()
/// .insert(header::CONTENT_TYPE, header::HeaderValue::from_static("Error"));
/// Ok(ErrorHandlerResponse::Response(res))
/// }
///
2019-11-21 08:52:33 +00:00
/// let app = App::new()
/// .wrap(
/// ErrorHandlers::new()
/// .handler(StatusCode::INTERNAL_SERVER_ERROR, render_500),
2019-11-21 08:52:33 +00:00
/// )
/// .service(web::resource("/test")
/// .route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed())
/// ));
/// ```
pub struct ErrorHandlers<B> {
handlers: Handlers<B>,
}
type Handlers<B> = Rc<AHashMap<StatusCode, Box<ErrorHandler<B>>>>;
impl<B> Default for ErrorHandlers<B> {
fn default() -> Self {
ErrorHandlers {
2021-01-04 04:29:07 +00:00
handlers: Rc::new(AHashMap::default()),
}
}
}
impl<B> ErrorHandlers<B> {
/// Construct new `ErrorHandlers` instance.
pub fn new() -> Self {
ErrorHandlers::default()
}
/// Register error handler for specified status code.
pub fn handler<F>(mut self, status: StatusCode, handler: F) -> Self
where
F: Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> + 'static,
{
Rc::get_mut(&mut self.handlers)
.unwrap()
.insert(status, Box::new(handler));
self
}
}
impl<S, B> Transform<S, ServiceRequest> for ErrorHandlers<B>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Transform = ErrorHandlersMiddleware<S, B>;
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
let handlers = self.handlers.clone();
Box::pin(async move { Ok(ErrorHandlersMiddleware { service, handlers }) })
}
}
2019-03-24 18:32:30 +00:00
#[doc(hidden)]
pub struct ErrorHandlersMiddleware<S, B> {
service: S,
handlers: Handlers<B>,
}
impl<S, B> Service<ServiceRequest> for ErrorHandlersMiddleware<S, B>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = ErrorHandlersFuture<S::Future, B>;
actix_service::forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let handlers = self.handlers.clone();
2019-11-21 08:52:33 +00:00
let fut = self.service.call(req);
ErrorHandlersFuture::ServiceFuture { fut, handlers }
}
}
2019-11-21 08:52:33 +00:00
pin_project! {
#[project = ErrorHandlersProj]
pub enum ErrorHandlersFuture<Fut, B>
where
Fut: Future,
{
ServiceFuture {
#[pin]
fut: Fut,
handlers: Handlers<B>,
},
HandlerFuture {
fut: LocalBoxFuture<'static, Fut::Output>,
},
}
}
impl<Fut, B> Future for ErrorHandlersFuture<Fut, B>
where
Fut: Future<Output = Result<ServiceResponse<B>, Error>>,
{
type Output = Fut::Output;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.as_mut().project() {
ErrorHandlersProj::ServiceFuture { fut, handlers } => {
let res = ready!(fut.poll(cx))?;
match handlers.get(&res.status()) {
Some(handler) => match handler(res)? {
ErrorHandlerResponse::Response(res) => Poll::Ready(Ok(res)),
ErrorHandlerResponse::Future(fut) => {
self.as_mut()
.set(ErrorHandlersFuture::HandlerFuture { fut });
self.poll(cx)
}
},
None => Poll::Ready(Ok(res)),
}
}
ErrorHandlersProj::HandlerFuture { fut } => fut.as_mut().poll(cx),
2019-11-21 08:52:33 +00:00
}
}
}
#[cfg(test)]
mod tests {
2019-05-12 15:34:51 +00:00
use actix_service::IntoService;
2021-04-01 14:26:13 +00:00
use actix_utils::future::ok;
use futures_util::future::FutureExt as _;
use super::*;
use crate::http::{
header::{HeaderValue, CONTENT_TYPE},
StatusCode,
};
2019-11-26 05:25:50 +00:00
use crate::test::{self, TestRequest};
use crate::HttpResponse;
2021-03-08 20:32:19 +00:00
#[allow(clippy::unnecessary_wraps)]
fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
res.response_mut()
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("0001"));
Ok(ErrorHandlerResponse::Response(res))
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_handler() {
let srv = |req: ServiceRequest| {
ok(req.into_response(HttpResponse::InternalServerError().finish()))
};
let mw = ErrorHandlers::new()
2019-11-26 05:25:50 +00:00
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500)
.new_transform(srv.into_service())
.await
.unwrap();
2021-02-11 23:03:17 +00:00
let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
}
2021-03-08 20:32:19 +00:00
#[allow(clippy::unnecessary_wraps)]
fn render_500_async<B: 'static>(
mut res: ServiceResponse<B>,
) -> Result<ErrorHandlerResponse<B>> {
res.response_mut()
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("0001"));
2019-11-21 08:52:33 +00:00
Ok(ErrorHandlerResponse::Future(ok(res).boxed_local()))
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_handler_async() {
let srv = |req: ServiceRequest| {
ok(req.into_response(HttpResponse::InternalServerError().finish()))
};
let mw = ErrorHandlers::new()
2019-11-26 05:25:50 +00:00
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500_async)
.new_transform(srv.into_service())
.await
.unwrap();
2021-02-11 23:03:17 +00:00
let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
}
}