I'm using Spring (4.0.4) MVC to build a RESTful API. I need to return a ResponseEntity with a JSON representation of an error with http status 404.
However, when I make a request that results in a 404, instead of seeing the error JSON, I get the following output:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /project/api/resource/100 was not found on this server.</p>
<p>Additionally, a 503 Service Temporarily Unavailable
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
From this stackoverflow post, I've found that I can prevent this error page from being sent in place of the the error by including the following parameter in my web.xml
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
And using the a global advice similar to this:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public ResponseEntity<ErrorResponse> requestHandlingNoHandlerFound(HttpServletRequest req,
NoHandlerFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setText("error response");
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
However, when I add this MyExceptionHandler class, I am getting the following exception:
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.servlet.NoHandlerFoundException]: {public org.springframework.http.ResponseEntity com.rest.MyExceptionHandler.requestHandlingNoHandlerFound
The issue is that it doesn't know whether to call my custom ExceptionHandler or the one defined in web.servlet.
How can I resolve this issue so that I am able to return JSON from an API using Spring?
Here's what I think is happening:
Your
@ControllerAdvice
class extendsResponseEntityExceptionHandler
which has a methodhandleNoHandlerFoundException
(see at the end of the this file in the source code) Also, you have an @ExceptionHandler annotated method to handle the same exception.I think having both of them in your code is causing this issue.
So either:
I think either of those options should work.