Is there a throws proposal on the REST endpoint that is considered bad design?
I would like to exclude Exceptions from my REST endpoints. However, I am not very good at 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 only return 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 get a representation of the DuplicateDataException using the 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 the response is returned in the end one way or another, but is one way to handle exceptions (regardless of whether they are RuntimeExceptions) preferred over the other, or does it not really matter? I have never seen cast statements on a REST endpoint, so I am asking.
Please note that this question or this question did not provide the answer I am looking for.
source to share
If the parent class catches the thrown exception and returns the appropriate HTTP response error code (4xx), the original code is fine.
If there is no parent class catching them to make them 4xx instead of 500, your code - changing your response code to something appropriate for this particular error - seems like a really good idea.
source to share
Bad idea is an exception.
From the client's point of view, it raises an http 500 error code that doesn't tell the automatic program anything.
You should build your code trying to catch all possible errors and respond with the appropriate error code within your valid response. If your answer in json answered something like the following:
{
statusCode: 345,
errorMessage: 'The error code message'
}
Leave the http 500 status code unexpected.
source to share