How can I return 404 http status from dropwizard

new for dropwizard! is there anyway that I can manually return different http status codes from apis? basically something like this!

@GET @Timed public MyObject getMyObject(@QueryParam("id") Optional<String> id) { MyObj myObj = myDao.getMyObject(id) if (myObj == null) { //return status.NOT_FOUND; // or something similar // or more probably // getResponseObjectFromSomewhere.setStatus(mystatus) } return myObj; } 
+5
source share
3 answers

I would recommend using a JAX-RS Response object instead of returning your actual domain object in response. It serves as an excellent standard for including metadata with your response object and provides a good constructor for handling status codes, headers, client content types, etc.

 //import javax.ws.rs.core.Response above @GET @Timed public Response getMyObject(@QueryParam("id") Optional<String> id) { MyObject myObj = myDao.getMyObject(id) if (myObj == null) { //you can also provide messaging or other metadata if it is useful return Response.status(Response.Status.NOT_FOUND).build() } return Response.ok(myObj).build(); } 
+6
source

It is as simple as throwing a WebApplicationException .

 @GET @Timed public MyObject getMyObject(@QueryParam("id") Optional<String> id) { MyObject myObj = myDao.getMyObject(id) if (myObj == null) { throw new WebApplicationException(404); } return myObj; } 

As you move forward, you can collect custom exceptions that you can read here .

+9
source

The easiest way is to return an Optional<MyObject> . Dropwizard automatically returns 404 when your result is Optional.absent() or Optional.empty() if you use the dropwizard-java8 package.

Just do:

 @GET @Timed public Optional<MyObject> getMyObject(@QueryParam("id") Optional<String> id) { Optional<MyObject> myObjOptional = myDao.getMyObject(id) return myObjOptional; } 

Obviously, you need to update your DAO according to the return of Optional.fromNullable(get(id)) for Guava or Optional.ofNullable(get(id)) for the Java8 package.

There is no need to play with custom Response objects if you do not want to return a custom status code beyond 200 and 404

+4
source

Source: https://habr.com/ru/post/1215556/


All Articles