Sé que esto es viejo, pero estaba buscando una solución para esto también y no pude encontrar nada. Estamos proporcionando servicios RESTful utilizando Spring y estamos cargando archivos y no estábamos seguros de cómo manejar esto. Se me ocurrió lo siguiente y espero que sea útil a alguien:
Todos nuestros excepciones se manejan con anotaciones, así que tenemos puesta en marcha nuestra resolución de manipulador de error como este:
@Configuration
public class MyConfig{
@Bean
public AnnotationMethodHandlerExceptionResolver exceptionResolver(){
final AnnotationMethodHandlerExceptionResolver resolver = new AnnotationMethodHandlerExceptionResolver();
resolver.setMessageConverters(messageConverters());
resolver;
}
}
A continuación, una común clase que puede manejar la excepción
public class MultipartExceptionHandler
{
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseStatus(value = HttpStatus.PRECONDITION_FAILED)
@ResponseBody
protected CustomError handleMaxUploadSizeExceededException(final HttpServletRequest request,
final HttpServletResponse response, final Throwable e)
throws IOException
{
logger.error(e);
CustomError c = new CustomErrorMaxFileSize("Max file size exceeded", MAX_FILE_SIZE);
return c;
}
@ExceptionHandler(MultipartException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
protected CustomError handleGenericMultipartException(final HttpServletRequest request,
final HttpServletResponse response, final Throwable e)
throws IOException
{
logger.error(e);
CustomError c = new CustomErrorGeneric("There was a problem with the upload");
return c;
}
}
Luego subclase del patrimonio común de resolución de varias partes e implementar la interfaz HandlerExceptionResolver
@Component(value="multipartResolver") // Spring expects this name
public class MyMultipartResolver extends CommonsMultipartResolver implements HandlerExceptionResolver
{
// This is the Spring bean that handles exceptions
// We defined this in the Java configuration file
@Resource(name = "exceptionResolver")
private AnnotationMethodHandlerExceptionResolver exceptionResolver;
// The multipart exception handler with the @ExceptionHandler annotation
private final MultipartExceptionHandler multipartExceptionHandler = new MultipartExceptionHandler();
// Spring will call this when there is an exception thrown from this
// multipart resolver
@Override
public ModelAndView resolveException(
final HttpServletRequest request,
final HttpServletResponse response,
final Object handlerParam,
final Exception ex)
{
// Notice that we pass this.multipartExceptionHandler
// and not the method parameter 'handlerParam' into the
// exceptionResolver. We do this because the DispatcherServlet
// doDispatch() method calls checkMultipart() before determining
// the handler for the request. If doing the multipart check fails
// with a MultipartException, Spring will never have a reference
// to the handler and so 'handlerParam' will be null at this point.
return exceptionResolver.resolveException(request, response, this.multipartExceptionHandler, ex);
}
}
Tenga en cuenta que al establecer 'fileItems = Collections.EMPTY_LIST;', todos los parámetros de solicitud se descartan. En otras palabras, 'request.getParameterMap()' será '{}'. –
El comentario de @Markus es especialmente importante a tener en cuenta si uno de los parámetros de solicitud es un token csrf. Al establecer 'fileItems = Collections.EMPTY_LIST;' se descarta el token CSRF, haciendo que el filtro CSRF trate esta solicitud como inválida. –