使用Spring MVC处理MaxUploadSizeExceededException


问题内容

超出文件大小时,如何通过文件上传拦截和发送自定义错误消息。我在控制器类中有一个带注释的异常处理程序,但是请求没有到达控制器。我在此链接上遇到的答案如何处理MaxUploadSizeExceededException建议实现HandlerExceptionResolver。

在Spring 3.5中发生了什么变化还是还是唯一的解决方案?


问题答案:

我最终实现了HandlerExceptionResolver:

@Component public class ExceptionResolverImpl implements HandlerExceptionResolver {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionResolverImpl.class);

@Override
public ModelAndView resolveException(HttpServletRequest request,
        HttpServletResponse response, Object obj, Exception exc) {

    if(exc instanceof MaxUploadSizeExceededException) {
        response.setContentType("text/html");
        response.setStatus(HttpStatus.REQUEST_ENTITY_TOO_LARGE.value());

        try {
            PrintWriter out = response.getWriter();

            Long maxSizeInBytes = ((MaxUploadSizeExceededException) exc).getMaxUploadSize();

            String message = "Maximum upload size of " + maxSizeInBytes + " Bytes per attachment exceeded";
            //send json response
            JSONObject json = new JSONObject();

            json.put(REConstants.JSON_KEY_MESSAGE, message);
            json.put(REConstants.JSON_KEY_SUCCESS, false);

            String body = json.toString();

            out.println("<html><body><textarea>" + body + "</textarea></body></html>");

            return new ModelAndView();
        }
        catch (IOException e) {
            LOG.error("Error writing to output stream", e);
        }
    }

    //for default behaviour
    return null;
}

}