Add support for error transformation

This commit is contained in:
asonix 2020-06-13 13:50:51 -05:00
parent 6985ce5e86
commit 41efb3153d
3 changed files with 33 additions and 6 deletions

View file

@ -31,7 +31,7 @@ use actix_web::{
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Error in file function, {0}")]
#[error("{0}")]
FileFn(#[from] actix_web::Error),
#[error("Error parsing payload, {0}")]
Payload(#[from] PayloadError),

View file

@ -101,7 +101,16 @@ where
let fut = self.service.call(req);
Box::pin(async move {
let uploaded = handle_multipart(multipart, form).await?;
let uploaded = match handle_multipart(multipart, form.clone()).await {
Ok(uploaded) => uploaded,
Err(e) => {
if let Some(f) = form.transform_error.clone() {
return Err((f)(e));
} else {
return Err(e.into());
}
}
};
let _ = tx.send(uploaded);
fut.await
})

View file

@ -468,10 +468,11 @@ impl Map {
/// ```
#[derive(Clone)]
pub struct Form {
pub max_fields: u32,
pub max_field_size: usize,
pub max_files: u32,
pub max_file_size: usize,
pub(crate) max_fields: u32,
pub(crate) max_field_size: usize,
pub(crate) max_files: u32,
pub(crate) max_file_size: usize,
pub(crate) transform_error: Option<Arc<dyn Fn(crate::error::Error) -> actix_web::Error>>,
inner: Map,
}
@ -479,16 +480,33 @@ impl Form {
/// Create a new form
///
/// If you wish to provide your own executor, use the `with_executor` method.
///
/// Default values are as follows
/// - max_fields: 100
/// - max_field_size: 10_000 bytes
/// - max_files: 20
/// - max_files_size: 10_000_000 bytes
pub fn new() -> Self {
Form {
max_fields: 100,
max_field_size: 10_000,
max_files: 20,
max_file_size: 10_000_000,
transform_error: None,
inner: Map::new(),
}
}
/// Add an optional error handler to transform errors produced by the middleware
pub fn transform_error(
mut self,
f: impl Fn(crate::error::Error) -> actix_web::Error + 'static,
) -> Self {
self.transform_error = Some(Arc::new(f));
self
}
/// Set the maximum number of fields allowed in the upload
///
/// The upload will error if too many fields are provided.