new to dropwizard! is there anyway that I can manually return different http status codes from the apis? basically something similar to 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;
}
The simplest way is to return an Optional<MyObject>
. Dropwizard will automatically throw a 404 when your result is Optional.absent()
or Optional.empty()
if you use the dropwizard-java8 bundle.
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 by returning Optional.fromNullable(get(id))
for Guava or Optional.ofNullable(get(id))
for Java8 bundle.
There is no need to play around with custom Response
objects unless you want to return a custom status code outside of 200
and 404
It's 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 get further along you may want to put together custom exceptions which you can read more about here.
I would recommend using the JAX-RS Response object instead of returning your actual domain object in the response. It serves as an excellent standard for including metadata with your response object and provides a nice builder for handling status codes, headers, customer 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();
}
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