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
}
jax
  • 37,735
  • 57
  • 182
  • 278
  • Instead of an interceptor, you might want to try `@ControllerAdvice` with an `@ExceptionHandler` method(s). See this other SO answer: http://stackoverflow.com/a/16313685/1174467 – superEb Jul 28 '13 at 23:45
  • Also see this SO question: http://stackoverflow.com/questions/12977368/how-to-change-the-content-type-in-exception-handler – superEb Jul 28 '13 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. – jax Jul 29 '13 at 01: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. – superEb Aug 07 '13 at 22:07

0 Answers0