我正在使用 Spring Boot v1.2.5 创建 REST 应用程序。上传图片时,我检查了最大文件大小,这是提供的属性:
multipart.maxFileSize= 128KB
在 application.properties 中。此功能由 Spring Boot 本身提供。现在检查工作正常。问题是,我如何处理异常并返回一个他能理解的消息给用户?
更新 1----------
我在我的 Controller 中编写了一个方法,我打算在其中使用@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
here来处理这种特殊情况。我相信,我们也可以使用DefaultHandlerExceptionResolver
,但ResponseEntityExceptionHandler
允许我们返回 a ResponseEntity
,而不是前者,后者的方法将返回ModelAndView
。我还没有尝试过。
这是我用来处理的最终代码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;
}
}