From 98c99f3bc2e9f706287944f38c4c7c25495a74f8 Mon Sep 17 00:00:00 2001 From: Rob Ede Date: Mon, 13 Feb 2023 23:40:23 +0000 Subject: [PATCH] add methods for mapping error responses --- actix-web/src/error/error.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/actix-web/src/error/error.rs b/actix-web/src/error/error.rs index 3a5a128f6..599bf4c56 100644 --- a/actix-web/src/error/error.rs +++ b/actix-web/src/error/error.rs @@ -6,7 +6,7 @@ use crate::{HttpResponse, ResponseError}; /// General purpose Actix Web error. /// -/// An Actix Web error is used to carry errors from `std::error` through actix in a convenient way. +/// An Actix Web error is used to carry errors from `std::error` through Actix in a convenient way. /// It can be created through converting errors with `into()`. /// /// Whenever it is created from an external object a response error is created for it that can be @@ -14,6 +14,7 @@ use crate::{HttpResponse, ResponseError}; /// you can always get a `ResponseError` reference from it. pub struct Error { cause: Box, + response_mappers: Vec HttpResponse>>, } impl Error { @@ -29,7 +30,20 @@ impl Error { /// Shortcut for creating an `HttpResponse`. pub fn error_response(&self) -> HttpResponse { - self.cause.error_response() + let mut res = self.cause.error_response(); + + for mapper in &self.response_mappers { + res = (mapper)(res); + } + + res + } + + pub fn add_mapper(&mut self, mapper: F) + where + F: Fn(HttpResponse) -> HttpResponse + 'static, + { + self.response_mappers.push(Box::new(mapper)) } } @@ -56,6 +70,7 @@ impl From for Error { fn from(err: T) -> Error { Error { cause: Box::new(err), + response_mappers: Vec::new(), } } }