Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In that example I only throw an exception when you try to delete a student who doesn't exist. The reason I do so is that it contains semantic information which is useful for the client.

If I returned a fake value - the client would get a 200 response on his attempt to delete a non-existent resource, which is clearly the incorrect behavior. I could return nothing - but then the client would see a 204. So, I choose to throw an exception with a response 'NOT_FOUND'

  throw new WebApplicationException(Response.Status.NOT_FOUND);
so that the client gets a 404 response.


I did try and build your code to run the test (I've no idea where the CsvParam and DateParam classes come from) but I think that the following will give you what you want without throwing the exception.

  @DELETE
  @Path("{uid: [0-9]+}")
  public Response deleteStudent(@PathParam("uid") int uid) {
    final Student deletedStudent = STUDENTS.remove(uid);

    if (deletedStudent == null) {
      return Response.status(Response.Status.NOT_FOUND).build();
    } else {
      return Response.ok().entity(true).build();
    }
  }


Ah, I see what you mean - thanks!

The full (buildable) source code - including the CsvParam and DateParam classes - are here: https://github.com/smanek/students


Yes, this is only an example.

There are a few things I'd like to point out to add to this example:

1) JAX-RS is still new. In the future, they might improve the exception handling or whatnot (so if you return null, they might decided to return 404 ... who knows)

2) We can always wrap all JAX-RS with a Filter. So you can throw JPA level exception (not found) and let the filter catch it and convert it to WebApplicationException(404). Thus in theory, your JAX-RS implementation won't have any RuntimeException explicitly in the code.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: