05 REST Error Handling
HTTP Status Codes
Success - ranges from 200 to 399. Ex. 200 is OK
Failure - ranges from 400 to 599
In Rest there are two types of error: standard errors and application error.
Standard errors are common across RESTful applications, no matter which language or which type of restful web applications you build, they have standard errors. For example, a client uses a wrong URI.
For example our patientService might have errors which are very specific to hospital management. Another application could have its own application errors.
How to return standard http error codes back to client JaxRS?
Web Application Error - Uses class called WebApplicationException(Response.Status.NOT_FOUND) where we create an instance of this class object and provide the status code. Apache CXF or JAXRS providers like Jersey will convert this into appropriate http message and send it to the client.
@Override public Patient getPatient(Long id) { if(patients.get(id)==null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return patients.get(id); }
Using JAXRS (javax.ws.rs) exception - JAXRS comes with some expection like 400 for BadRequestException, NotAuthoried (401), Forbidden Exception(403), InternalServerException(500) and ServiceUnavialiableException(503)
@Override
public Patient getPatient(Long id) {
if(patients.get(id)==null) {
throw new NotFoundException();
}
return patients.get(id);
}Throw Custom Exception
If an exception is thrown by a data access layer or a services layer we need to handle that exception in the restful layer and send a user friendly message back to the client and to do that the Jaxrs API provides us a concept or tool called exception.
Mappers these exception mappers are classes that we write which can handle a particular type of exception that is raised in our application and they will send back a user friendly message so when an exception is thrown automatically this exception mappers will be used by the underlaying providers like CXF and what ever message these exception methods return for that exception that will be sent to the client.
Question 1:
Which JAX-RS exception can be thrown with any error status code? →WebApplicationException
InternalServerError
NotFoundException
WebApplicationException
ServiceUnAvailableException
Question 2:
Which JAX-RS exception should be thrown when the client uses a mal-formed URL? →BadRequestException
ServiceUnAvailableException
BadRequestException
InternalServerError
NotFoundException
Question 3:
What can be used to handle Business Exceptions in a generic fashion? → Exception Mappers
Exception Handlers
WebApplicationException
Interceptors
Exception Mappers
Question 4:
Which annotation should be used to mark the ExceptionMapper classes to register them with the JAX-RS runtime? → Provider
Exception
Provider
Mapper
Resource