Reputation: 125396
I have a JAX-RS resource class that can return a 404 response when a certain request is made. Unfortunately, even though the operation's method is annotated @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
, a 404 Response object always results in Tomcat shoving its own "not found" HTML error page into the body.
This is breaking clients that expect XML/JSON responses. How do I shut Tomcat up in these cases?
My code looks like this now:
@GET
@Path("isbn/{isbn}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response isbn(@PathParam("isbn") String isbn) {
ProductSearchDO productSearch = ProductSvc.find( isbn );
if (productSearch == null)
return Responses.notFound().build();
return Response.ok( productSearch ).tag( String.valueOf( productSearch.hashCode() ) ).build();
}
Upvotes: 3
Views: 2757
Reputation: 31
404 Not Found
is a client error meaning that the problem is on the client's side for requesting a non-existent page. In this case, it makes makes sense to return a 404.
I'd argue that the client should be able to appropriately handle a 404 response. You as a server are doing your due diligence by returning an error code. It's up to the client to be able to handle the response.
Upvotes: 0
Reputation: 11337
You shouldn't return a 404. Just return an empty JSON, then your client will be able to handle it.
This approach is called "soft 404" (if I'm not wrong).
This approach is used also in Facebook:
https://graph.facebook.com/search?q=nlknrekjfndjkfnsjkefbnejkrbfjedbfjekfbekj
EDIT:
I'll explain it better. As the W3C says the 404 should be used if
The server has not found anything matching the Request-URI.
Actually your server has found a matching Request-URI, but simply the response will be empty. And also
This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.
You can apply another kind of response if you want.
If you still want to go your way you can try to override the standard Tomcat 404 page with an empty page, or ask to the client side to check for the status code
if(statusCode==404) { blablabla }
EDIT2:
A downvote for what? I don't think my answer is wrong, you can like it or not, but I don't think it's actually a wrong one.
In your case you're doing a research for a certain product. If you cannot find any product matching your search why you should return a 404?
More sources about this:
Should a RESTful API return 404 for arrays of objects?
also here:
Querystring in REST Resource url
"If the URL returns a search result then it shouldn't return a 404."
and same here:
REST: Mapping 404 HTTP Status codes especially the comment:
Simply, "no results" is a valid search result. The resource exists, it's representation is simply "empty". So, 404 is not justified.
Upvotes: 2