how can i return 404 http status from dropwizard

nightograph picture nightograph · Mar 17, 2015 · Viewed 7.3k times · Source

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;
}

Answer

condit picture condit · Mar 17, 2015

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.