Spring @ExceptionHandler does not work with @ResponseBody

后端 未结 7 1383
南笙
南笙 2020-11-29 23:45

I try to configure a spring exception handler for a rest controller that is able to render a map to both xml and json based on the incoming accept header. It throws a 500 se

相关标签:
7条回答
  • 2020-11-30 00:52

    The following could be a workaround if you are using message converters to marshall error objects as the response content

    @ExceptionHandler(IllegalArgumentException.class)
    public String handleException(final Exception e, final HttpServletRequest request)
    {
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("errorCode", 1234);
        map.put("errorMessage", "Some error message");
        request.setAttribute("error", map);
        return "forward:/book/errors"; //forward to url for generic errors
    }
    
    //set the response status and return the error object to be marshalled
    @SuppressWarnings("unchecked")
    @RequestMapping(value = {"/book/errors"}, method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody Map<String, Object> showError(HttpServletRequest request, HttpServletResponse response){
    
        Map<String, Object> map = new HashMap<String, Object>();
        if(request.getAttribute("error") != null)
            map = (Map<String, Object>) request.getAttribute("error");
    
        response.setStatus(Integer.parseInt(map.get("errorCode").toString()));
    
        return map;
    }
    
    0 讨论(0)
提交回复
热议问题