2021-01-05 09:51:58 +00:00
|
|
|
//! For middleware documentation, see [`ErrorHandlers`].
|
|
|
|
|
2021-01-14 01:43:44 +00:00
|
|
|
use std::{
|
|
|
|
future::Future,
|
|
|
|
pin::Pin,
|
|
|
|
rc::Rc,
|
|
|
|
task::{Context, Poll},
|
|
|
|
};
|
2019-03-10 23:35:38 +00:00
|
|
|
|
|
|
|
use actix_service::{Service, Transform};
|
2021-01-04 04:29:07 +00:00
|
|
|
use ahash::AHashMap;
|
2021-01-14 01:43:44 +00:00
|
|
|
use futures_core::{future::LocalBoxFuture, ready};
|
2021-11-30 11:16:53 +00:00
|
|
|
use pin_project_lite::pin_project;
|
2019-03-10 23:35:38 +00:00
|
|
|
|
2021-01-05 09:51:58 +00:00
|
|
|
use crate::{
|
|
|
|
dev::{ServiceRequest, ServiceResponse},
|
|
|
|
http::StatusCode,
|
2021-06-17 16:57:58 +00:00
|
|
|
Error, Result,
|
2021-01-05 09:51:58 +00:00
|
|
|
};
|
2019-03-10 23:35:38 +00:00
|
|
|
|
2021-01-05 09:51:58 +00:00
|
|
|
/// Return type for [`ErrorHandlers`] custom handlers.
|
2019-03-10 23:35:38 +00:00
|
|
|
pub enum ErrorHandlerResponse<B> {
|
2021-01-05 09:51:58 +00:00
|
|
|
/// Immediate HTTP response.
|
2019-03-10 23:35:38 +00:00
|
|
|
Response(ServiceResponse<B>),
|
2021-01-05 09:51:58 +00:00
|
|
|
|
|
|
|
/// A future that resolves to an HTTP response.
|
2019-11-21 08:52:33 +00:00
|
|
|
Future(LocalBoxFuture<'static, Result<ServiceResponse<B>, Error>>),
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
|
2019-07-17 09:48:37 +00:00
|
|
|
type ErrorHandler<B> = dyn Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>;
|
2019-03-10 23:35:38 +00:00
|
|
|
|
2021-01-05 09:51:58 +00:00
|
|
|
/// Middleware for registering custom status code based error handlers.
|
2019-03-10 23:35:38 +00:00
|
|
|
///
|
2021-01-05 09:51:58 +00:00
|
|
|
/// 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.
|
2019-03-10 23:35:38 +00:00
|
|
|
///
|
2021-02-10 12:10:03 +00:00
|
|
|
/// # Examples
|
2021-03-25 08:45:52 +00:00
|
|
|
/// ```
|
2021-01-05 09:51:58 +00:00
|
|
|
/// use actix_web::middleware::{ErrorHandlers, ErrorHandlerResponse};
|
2021-12-05 14:37:20 +00:00
|
|
|
/// use actix_web::{web, dev, App, HttpRequest, HttpResponse, Result};
|
|
|
|
/// use actix_web::http::{StatusCode, header};
|
2019-03-10 23:35:38 +00:00
|
|
|
///
|
|
|
|
/// fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
|
|
|
|
/// res.response_mut()
|
|
|
|
/// .headers_mut()
|
2021-12-05 14:37:20 +00:00
|
|
|
/// .insert(header::CONTENT_TYPE, header::HeaderValue::from_static("Error"));
|
2019-03-10 23:35:38 +00:00
|
|
|
/// Ok(ErrorHandlerResponse::Response(res))
|
|
|
|
/// }
|
|
|
|
///
|
2019-11-21 08:52:33 +00:00
|
|
|
/// let app = App::new()
|
|
|
|
/// .wrap(
|
|
|
|
/// ErrorHandlers::new()
|
2021-12-05 14:37:20 +00:00
|
|
|
/// .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())
|
|
|
|
/// ));
|
2019-03-10 23:35:38 +00:00
|
|
|
/// ```
|
|
|
|
pub struct ErrorHandlers<B> {
|
2021-01-14 01:43:44 +00:00
|
|
|
handlers: Handlers<B>,
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
|
2021-01-14 01:43:44 +00:00
|
|
|
type Handlers<B> = Rc<AHashMap<StatusCode, Box<ErrorHandler<B>>>>;
|
|
|
|
|
2019-03-10 23:35:38 +00:00
|
|
|
impl<B> Default for ErrorHandlers<B> {
|
|
|
|
fn default() -> Self {
|
|
|
|
ErrorHandlers {
|
2021-01-04 04:29:07 +00:00
|
|
|
handlers: Rc::new(AHashMap::default()),
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<B> ErrorHandlers<B> {
|
2021-01-05 09:51:58 +00:00
|
|
|
/// Construct new `ErrorHandlers` instance.
|
2019-03-10 23:35:38 +00:00
|
|
|
pub fn new() -> Self {
|
|
|
|
ErrorHandlers::default()
|
|
|
|
}
|
|
|
|
|
2021-01-05 09:51:58 +00:00
|
|
|
/// Register error handler for specified status code.
|
2019-03-10 23:35:38 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-03 23:47:04 +00:00
|
|
|
impl<S, B> Transform<S, ServiceRequest> for ErrorHandlers<B>
|
2019-03-10 23:35:38 +00:00
|
|
|
where
|
2021-01-14 01:43:44 +00:00
|
|
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
2019-03-10 23:35:38 +00:00
|
|
|
S::Future: 'static,
|
|
|
|
B: 'static,
|
|
|
|
{
|
|
|
|
type Response = ServiceResponse<B>;
|
|
|
|
type Error = Error;
|
|
|
|
type Transform = ErrorHandlersMiddleware<S, B>;
|
2021-01-03 23:47:04 +00:00
|
|
|
type InitError = ();
|
2021-01-14 01:43:44 +00:00
|
|
|
type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>;
|
2019-03-10 23:35:38 +00:00
|
|
|
|
|
|
|
fn new_transform(&self, service: S) -> Self::Future {
|
2021-01-14 01:43:44 +00:00
|
|
|
let handlers = self.handlers.clone();
|
|
|
|
Box::pin(async move { Ok(ErrorHandlersMiddleware { service, handlers }) })
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-24 18:32:30 +00:00
|
|
|
#[doc(hidden)]
|
2019-03-10 23:35:38 +00:00
|
|
|
pub struct ErrorHandlersMiddleware<S, B> {
|
|
|
|
service: S,
|
2021-01-14 01:43:44 +00:00
|
|
|
handlers: Handlers<B>,
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
|
2021-01-03 23:47:04 +00:00
|
|
|
impl<S, B> Service<ServiceRequest> for ErrorHandlersMiddleware<S, B>
|
2019-03-10 23:35:38 +00:00
|
|
|
where
|
2021-01-03 23:47:04 +00:00
|
|
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
2019-03-10 23:35:38 +00:00
|
|
|
S::Future: 'static,
|
|
|
|
B: 'static,
|
|
|
|
{
|
|
|
|
type Response = ServiceResponse<B>;
|
|
|
|
type Error = Error;
|
2021-01-14 01:43:44 +00:00
|
|
|
type Future = ErrorHandlersFuture<S::Future, B>;
|
2019-03-10 23:35:38 +00:00
|
|
|
|
2021-01-05 09:51:58 +00:00
|
|
|
actix_service::forward_ready!(service);
|
2019-03-10 23:35:38 +00:00
|
|
|
|
2021-02-07 01:00:40 +00:00
|
|
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
2019-03-10 23:35:38 +00:00
|
|
|
let handlers = self.handlers.clone();
|
2019-11-21 08:52:33 +00:00
|
|
|
let fut = self.service.call(req);
|
2021-01-14 01:43:44 +00:00
|
|
|
ErrorHandlersFuture::ServiceFuture { fut, handlers }
|
|
|
|
}
|
|
|
|
}
|
2019-11-21 08:52:33 +00:00
|
|
|
|
2021-11-30 11:16:53 +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>,
|
|
|
|
},
|
|
|
|
}
|
2021-01-14 01:43:44 +00:00
|
|
|
}
|
2019-03-10 23:35:38 +00:00
|
|
|
|
2021-01-14 01:43:44 +00:00
|
|
|
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)),
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
}
|
2021-01-14 01:43:44 +00:00
|
|
|
ErrorHandlersProj::HandlerFuture { fut } => fut.as_mut().poll(cx),
|
2019-11-21 08:52:33 +00:00
|
|
|
}
|
2019-03-10 23:35:38 +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 _;
|
2019-03-10 23:35:38 +00:00
|
|
|
|
|
|
|
use super::*;
|
2021-12-05 14:37:20 +00:00
|
|
|
use crate::http::{
|
|
|
|
header::{HeaderValue, CONTENT_TYPE},
|
|
|
|
StatusCode,
|
|
|
|
};
|
2019-11-26 05:25:50 +00:00
|
|
|
use crate::test::{self, TestRequest};
|
2019-03-10 23:35:38 +00:00
|
|
|
use crate::HttpResponse;
|
|
|
|
|
2021-03-08 20:32:19 +00:00
|
|
|
#[allow(clippy::unnecessary_wraps)]
|
2019-03-10 23:35:38 +00:00
|
|
|
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()))
|
|
|
|
};
|
|
|
|
|
2021-02-07 01:00:40 +00:00
|
|
|
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");
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
|
2021-03-08 20:32:19 +00:00
|
|
|
#[allow(clippy::unnecessary_wraps)]
|
2019-03-10 23:35:38 +00:00
|
|
|
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-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
|
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()))
|
|
|
|
};
|
|
|
|
|
2021-02-07 01:00:40 +00:00
|
|
|
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");
|
2019-03-10 23:35:38 +00:00
|
|
|
}
|
|
|
|
}
|