Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json response for 404/503 errors

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

like image 792
fedor.belov Avatar asked Jan 28 '14 11:01

fedor.belov


2 Answers

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.

like image 188
LiorH Avatar answered Nov 15 '22 17:11

LiorH


After few days I decided to throw new com.sun.jersey.api.NotFoundException() and process it by my custom WebApplicationExceptionMapper.

like image 26
fedor.belov Avatar answered Nov 15 '22 16:11

fedor.belov