Below is a web service which gives the latest version among all books with a given Id. //Resource controller
@Path("latestVersionBook/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getLatestVersionBook(long id){
bookList=service.getLatestVersionBook(id)
return Response.ok(bookList).build();
//backend Service Below is the service method that uses jpa to get the books
public getLatestVersionBook(long id){
Query query = entityManager.createQuery("from Books where id = :id");
query.setParameter("id", id);
return query.getResultList().get(0);
}
If the id is an invalid (for which no books exist in the table) this code will throw NullPointerException.
Since the transition from view layer would be UI presents list of IDs-->User sends requests for one of this ids.
So it is not a usual case in which the returned list will be null.Should I check for null or let the code throw NullPointerException and let the exception mapper generate the response as BAD_REQUEST.
If i check for null/return empty list then I have to check for the same in resource controller too to generate a Response with Bad_Request.
if(!bookList.isEmpty())
return Response.status(Status.BAD_REQUEST).build();
else
return Response.ok(bookList).build();
Also It doesn't appear to be a good thing to put such validation(which need DB access) at a level of input validation available in Jersey /Spring similar frameworks as I would be doing the same select in the service and during custom validation to check if Id is present.
What is a good practice to do such validations?
PS: I am not sure if the above code will give book object with the latest(last) id ,if id is an auto-increment field.And the query can be modified to fetch book only for last Id.However for above question assume this works