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<DuplicateDataException> {
@Override
public Response toResponse(DuplicateDataException e) {
ErrorMessage errorMessage = new ErrorMessage ("Activity names must be unique.", <HttpStatusNumber>, "<add documentation here>");
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.