I would like to throw Exceptions from my REST endpoints. However, I am not too familiar with good REST design techniques. Consider the following...
//note the throws clause
@POST
public Response saveNewActivity(@HeaderParam("sessionTokenString") String sessionTokenString, Activity activity) throws Exception {
Activity result = as.saveNewActivity(activity);
if (result == null) {
throw new DuplicateDataException("blah blah blah");
}
return Response.ok(result).build();
}
versus handling Exceptions and explicitly returning only responses
@POST
public Response saveNewActivity(@HeaderParam("sessionTokenString") String sessionTokenString, Activity activity) {
try {
Activity result = as.saveNewActivity(activity);
if (result == null) {
throw new DuplicateDataException("blah blah blah");
}
return Response.ok(result).build();
} catch (Exception e) {
return Response.status(Response.Status.SOME_STATUS).build();
}
}
I can have the DuplicateDataException mapped using ExceptionMapper as follows
public class DuplicateDataExceptionMapper implements ExceptionMapper {
@Override
public Response toResponse(DuplicateDataException e) {
ErrorMessage errorMessage = new ErrorMessage ("Activity names must be unique.", , "");
return Response.status(Status.NOT_FOUND).entity(errorMessage).build();
}
}
Although in the end a Response gets returned anyways, but is one way of handling Exceptions (whether or not they are RuntimeExceptions) preferred over another, or does it not really matter? I have never seen a throws statement on a REST endpoint which is why I ask.
Please note that
this question or this question did not give the answer I am looking for.
Answer
If a parent class is catching the thrown exception and returning an appropriate HTTP Reponse error code (4xx), the initial code is fine.
If there's no parent class catching these to make them a 4xx instead of a 500, your code - to change the response code to something appropriate for this specific error - seems like a really good idea.
No comments:
Post a Comment