0

If I have a method such as the following in a Controller:

@RequestMapping(value = "/mymapping",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public final JsonResponse<?> myMethod() {

When the method throws an exception, I want a MVC interceptor to catch it and return a JSON error. I only want this to work for produces = MediaType.APPLICATION_JSON_VALUE methods in the controller.

How can I do this in my afterCompletion of HandlerInterceptor. If I inspect the contentType of the response it is null when an exception occurs.

@Override
public void afterCompletion(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
    //TODO
}
4
  • Instead of an interceptor, you might want to try @ControllerAdvice with an @ExceptionHandler method(s). See this other SO answer: stackoverflow.com/a/16313685/1174467 Commented Jul 28, 2013 at 23:45
  • Also see this SO question: stackoverflow.com/questions/12977368/… Commented Jul 28, 2013 at 23:51
  • @superEb this will cause all @ExceptionHandler to be called for all mappings regardless of their content type. (XML and Json will return a JsonResponse). I only want methods that produce json be processed by the exception handler. Commented Jul 29, 2013 at 1:44
  • Can you check the Accept header of the request in your interceptor method instead? Maybe populate a custom request attribute before re/throwing the exception in controller method? Can you apply a different interceptor to controllers that produce different data formats? Sorry, it seems like there are multiple ways to address this, but probably not the exact way you're looking for. Commented Aug 7, 2013 at 22:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.