Send message to client when HTTP method is not supported

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

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

      

I have an exception handler:

@ResponseBody
@ExceptionHandler(Throwable.class)
public ResponseEntity<?> exceptionHandler() {

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

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

      

But in this case it does not cause errors.

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

+3


source to share


1 answer


The problem is that SpringMVC doesn't find any method for HEAD in your controller, so it doesn't use it, and your @ExceptionHandler isn't used. It will be used for the exception thrown inside the controller. Excerpt from Spring Framework Reference: You use the @ExceptionHandler method annotation in the controller to specify which method is called when an exception of a particular type is thrown during the execution of controller methods (emphasis mine).



To handle the exception outside of any controller, you must register a HandlerExceptionResolver

bean that will replace the DefaultHandlerExceptionResolver

default Spring MVC provided. You can either put the Json String directly in the response and return null from the method resolve

(my preferred way), or you can put the elements in the model and use the view to format the Json.

+1


source







All Articles