我正在使用 Spring Boot v1.2.5 创建 REST 应用程序。上传图像时,我会检查最大文件大小,该属性提供了以下属性:
multipart.maxFileSize= 128KB
在应用程序属性中。该功能由 Spring Boot 本身提供。现在检查工作正常。问题是,如何处理异常并向用户返回他可以理解的消息?
更新1----------
我在控制器中编写了一个方法,我打算在其中处理 MultipartException,使用@ExceptionHandler
。这似乎不起作用。
这是我的代码:
@ExceptionHandler(MultipartException.class)
@ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
public ApplicationErrorDto handleMultipartException(MultipartException exception){
ApplicationErrorDto applicationErrorDto = new ApplicationErrorDto();
applicationErrorDto.setMessage("File size exceeded");
LOGGER.error("File size exceeded",exception);
return applicationErrorDto;
}
更新2----------
在 @luboskrnac 指出之后,我设法想出了一个解决方案。我们可以用ResponseEntityExceptionHandler
这里来处理这个特殊情况。我相信,我们也可以使用DefaultHandlerExceptionResolver
, but ResponseEntityExceptionHandler
将允许我们返回ResponseEntity
,与前者相反,其方法将返回ModelAndView
. I have not不过尝试了一下。
这是我用来处理的最终代码MultipartException
:
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = Logger.getLogger(CustomResponseEntityExceptionHandler.class);
@ExceptionHandler(MultipartException.class)
@ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
@ResponseBody
public ApplicationErrorDto handleMultipartException(MultipartException exception){
ApplicationErrorDto applicationErrorDto = new ApplicationErrorDto();
applicationErrorDto.setMessage("File size exceeded");
LOGGER.error("File size exceeded",exception);
return applicationErrorDto;
}
}
I am using Swagger for developing/documenting REST Apis. This is the response upon uploading a file that exceeds the size.
Thanks.