【问题标题】:Spring REST Multipart error handlingSpring REST Multipart 错误处理
【发布时间】:2014-04-07 16:33:25
【问题描述】:

我有这个 REST 控制器,它也应该处理异常。

@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
}
}

【问题讨论】:

    标签: java spring rest multipart multipartform-data


    【解决方案1】:

    这不是一个我不太满意的解决方案,而是一个有效的解决方案。我实现了HandlerExceptionResolver 接口来捕获所有异常。

    在实现的方法中,我只处理我感兴趣的异常。然后我向调用者发送一个错误代码并告诉他他做错了什么。

    @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}")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2021-09-25
      • 2017-02-08
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多