我有这个 REST Controller ,它也应该处理异常。
@ExceptionHandler(MultipartException.class)
注释不能像 explained 那样工作。 .
所以我正在实现HandlerExceptionResolver
,它基本上可以工作,但对于REST和JSON响应来说不如@ExceptionHandler
那么方便。
我想在 resolveException
中返回我的自定义类 ValidationReport
,类似于 @ExceptionHandler handleBadRequest
。我无法使用 ValidationReport
json 响应创建 ModelAndView。知道如何结合两种风格吗?
@RestController
class ValidationController implements HandlerExceptionResolver{
static Logger LOG = LoggerFactory.getLogger(ValidationController.class);
@RequestMapping(value="/validate", method=[POST])
public ValidationReport validate(MultipartFile file) {
LOG.info("received file ${file?.name}")
ValidationReport report = new ValidationReport();
return report
}
@ResponseStatus(BAD_REQUEST)
@ExceptionHandler(MultipartException.class)
@ResponseBody ValidationReport handleBadRequest(HttpServletRequest req, Exception ex) {
return new ValidationReport(USER_ERROR, "you should not upload files bigger then xx MB")
}
@Override
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof MultipartException){
response.sendError(BAD_REQUEST.value(),ex.message)
}
return null
}
}
我
最佳答案
这不是一个我不太满意的解决方案,而是一个有效的解决方案。我实现了 HandlerExceptionResolver 接口(interface)来捕获所有异常。
在实现的方法中,我只处理我感兴趣的异常。然后我向调用者发送错误代码并告诉他做错了什么。
@Override
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof MultipartException){
response.sendError(413,"Content is to big. Maximal allowed request size is: ${Application.MAX_REQUEST_SIZE}")
}
}
关于java - Spring REST 多部分错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918092/