Tuesday, 20 August 2013

Wrapping Standard HTTP Exceptions in Custom Response Using ResponseEntityExceptionHandler

Wrapping Standard HTTP Exceptions in Custom Response Using
ResponseEntityExceptionHandler

Background
I am creating a restful web service using Spring MVC 3.2.1.RELEASE. I
would like to be able to wrap the standard HTTP errors (400, 404, 500,
etc.) handled by the default exception handler resolvers with my own
response bodies and have those responses processed by MessageConverters
like any other response.
Example:
I would like my api to return the following for a 404 instead of the
standard message:
{
"status" : 404,
"message" : "The requested resource could not be found."
}
I have extended ResponseEntityExceptionHandler and overridden the
exception handling methods that I am interested in, but I cannot get
Spring to call my exception handler.


Question
How can I get Spring to call my subclass of ResponseEntityExceptionHandler?



What I Have Tried
I have implemented a custom exception handler that extends
ResponseEntityExceptionHandler and annotated it with @ControllerAdvice
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object>
handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException
ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage("The requested
resource could not be found.");
return new ResponseEntity<Object>(errorMessage,
HttpStatus.NOT_FOUND);
}
}
Based on the following quote in the javadocs for
ResponseEntityExceptionHandler
Note that in order for an {@code @ControllerAdvice} sub-class to be
detected, {@link ExceptionHandlerExceptionResolver} must be configured.
I added the following method to my Spring config:
@Configuration
@ComponentScan(basePackages = {"foo.app", "foo.app.common"})
@ImportResource({"classpath*:/foo-core-config.xml",
"classpath*:/applicationContext.xml"})
@PropertySource("classpath:env-config.properties")
public class FooAppConfiguration extends WebMvcConfigurationSupport
implements EnvironmentAware {
@Override
protected void
configureHandlerExceptionResolvers(List<HandlerExceptionResolver>
exceptionResolvers) {
ExceptionHandlerExceptionResolver resolver = new
ExceptionHandlerExceptionResolver();
resolver.setMessageConverters(getMessageConverters());
resolver.setOrder(Integer.MIN_VALUE);
resolver.setMappedHandlerClasses(new
Class[]{MyExceptionHandler.class});
exceptionResolvers.add(resolver);
}
}

No comments:

Post a Comment