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
}
@ControllerAdvicewith an@ExceptionHandlermethod(s). See this other SO answer: stackoverflow.com/a/16313685/1174467@ExceptionHandlerto 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.Acceptheader 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.