3

How can I intercept and send custom error messages with file upload when file size is exceeded. I have an annotated exception handler in the controller class, but the request does not come to the controller. The answer I came across on this link How to handle MaxUploadSizeExceededException suggests implementing HandlerExceptionResolver.

Have things changed in Spring 3.5 or is that still the only solution?

1 Answer 1

4

I ended up implementing 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;
}

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.