2012-01-25 87 views

回答

4

我最終實現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; 
} 

}