Aliaxander Aliaxander - 4 months ago 17
reST (reStructuredText) Question

Send message to a client when an HTTP method not supported

I've created a REST controller the can handle, as usual, GET, POST, PUT and DELETE HTTP requests using Spring MVC. The web server is Tomcat 8.
If a send request, for instance, with HEAD method, the response is an error page from Tomcat with message

HTTP Status 501 - Method LINK is not is not implemented by this servlet for this URI

I have such exception handler:

public ResponseEntity<?> exceptionHandler() {

Error error = createError("error_message.unforeseen_error");

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);

But it doesn't catch any error in this case.

Is there a way to send back a message wrapped in JSON object as a response instead of this Tomcat page?


The problem is that SpringMVC does not find any method for HEAD in your controller, so it does not use it and your @ExceptionHandler is not used. It would be used for exception arising inside the controller. Extract from Spring Frameword Reference : You use the @ExceptionHandler method annotation within a controller to specify which method is invoked when an exception of a specific type is thrown during the execution of controller methods (emphasis mine).

To process exception outside of any controller, you must register a HandlerExceptionResolver bean that will replace the DefaultHandlerExceptionResolver provided by default by Spring MVC. You could either directly put the Json String in the response and return null from resolve method (my prefered way), or put the elements in a model and use a view to format the Json.