Custom json response for internal exception in spring

714 views Asked by At

While implementing a global exception handler in Spring, I noticed that in case of a not recognized Accept header, Spring would throw it's own internal error. What I need is to return a custom JSON error structure instead. Works fine for application specific exceptions and totally fails for Spring HttpMediaTypeNotAcceptableException.

This code tells me "Failed to invoke @ExceptionHandler method: public java.util.Map RestExceptionHandler.springMalformedAcceptHeaderException()" when I try to request a page with incorrect Accept header. Any other way to return custom JSON for spring internal exceptions?

@ControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
    @ResponseBody
    public Map<String, String> springMalformedAcceptHeaderException() {

         Map<String, String> test = new HashMap<String, String>();
         test.put("test", "test");
         return test;
     }
} 
1

There are 1 answers

0
Leo On BEST ANSWER

Eventually figured that the only way is to do the json mapping manually.

@ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
@ResponseBody
public String springMalformedAcceptHeaderException(HttpServletResponse response) {
    // populate errorObj, set response headers, etc
    ObjectWriter jsonWriter = new ObjectMapper().writer();
    try {
        return  jsonWriter.writeValueAsString(errorObj);
    } catch(Exception e){}
    return "Whatever";
}