How to return JSON object in resolveException method of HandlerExceptionResolver in Spring MVC?
If you use the Spring 3.2 above, I recommend this way.
At first, declare the ControllerAdvice.
@Controller@ControllerAdvicepublic class JAttachfileApi extends BaseApi
And make the Exception Handler to response JSON Object as following.
@ExceptionHandler(MaxUploadSizeExceededException.class) public @ResponseBody Map<String,Object> handleMaxUploadSizeExceededException( MaxUploadSizeExceededException ex) { Map<String,Object> result = getResult(); JFileUploadJsonResponse errorResult = new JFileUploadJsonResponse(); errorResult.setError("Maximum upload size of "+ex.getMaxUploadSize()+" bytes exceeded."); List<JFileUploadJsonResponse> resultData = new ArrayList<JFileUploadJsonResponse>(); resultData.add(errorResult); result.put("files", resultData); return result; }
You simply can annotate the method resolveException as @ExceptionHandler() and then you can have its signature like any other controller method. So placing @ResponseBody before the return type should work.
"Much like standard controller methods annotated with a @RequestMapping annotation, the method arguments and return values of @ExceptionHandler methods can be flexible. For example, the HttpServletRequest can be accessed in Servlet environments and the PortletRequest in Portlet environments. The return type can be a String, which is interpreted as a view name, a ModelAndView object, a ResponseEntity, or you can also add the @ResponseBody to have the method return value converted with message converters and written to the response stream."