When I use 404
response code Dropwizard returns custom html code (even when Accept
header equals application/json
).
Controller method:
if (o == null) {
return Response.status(Response.Status.NOT_FOUND).build();
} else {
return Response.ok(o).build();
}
Dropwizard response:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /abc/1. Reason:
<pre> Not Found</pre></p><br/>
<br/>
...
</body>
</html>
How can I customize return body for 404
, 503
response codes (and etc) to return JSON?
ps
I have already implemented custom exceptions mappers. But I don't want to use exceptions for this task
you should use the type and entity methods of the response builder.
something like:
return Response
.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(error).build();
where error is serializable to json.
After few days I decided to throw new com.sun.jersey.api.NotFoundException()
and process it by my custom WebApplicationExceptionMapper
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With