How to return JSON object in resolveException method of HandlerExceptionResolver in Spring MVC?

4.8k views Asked by At

While implementing a File Uploader controller in Spring MVC I stucked with one problem. My code snap is given below.


@Controller
public class FileUploader extends AbstractBaseController implements HandlerExceptionResolver
{
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject handleFileUpload(@RequestParam("file") MultipartFile file)
    {
        JSONObject returnObj = new JSONObject();
        if (file.isEmpty())
        {
            returnObj.put("success", "false");
            returnObj.put("message", "File is empty");
        }
        else
        {
            try
            {
                //my file upload logic goes here 
            }
            catch (Exception e)
            {
                returnObj.put("success", "false");
                returnObj.put("message", "File not uploaded.");
            }
        }

        return returnObj;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception)
    {
        ModelAndView model = new ModelAndView();
        Map map = new HashMap();
        if (exception instanceof MaxUploadSizeExceededException)
        {
            // I want to return JSONObject from here like given below.
            /**
             * { "message":"File size exceeded", "success":"false" }
             * */
            map.put("message", "File size exceeded");
            map.put("success", "false");
            model.addObject(map);
        }
        return model;
    }
}


and my spring configuration look likes

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
    <property name="maxUploadSize" value="300000"/>
    </bean>

now In my controller I want to return JSONObject instead of ModelAndView in resolveException method in my controller as given in code snap because I am developing some like REST method to upload file.

any ideas? Thanks

2

There are 2 answers

3
angelodelia On

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."

2
mass On

If you use the Spring 3.2 above, I recommend this way.

  1. At first, declare the ControllerAdvice.

    @Controller
    @ControllerAdvice
    public class JAttachfileApi extends BaseApi
    
  2. 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;
        }