Saturday, 23 September 2017

Exception Handling in JAX-RS

In JAX-RS Implementation of REST, Each and every Exception should be handled as the Rest Exception as the OOTB Handles it , We can utilize the OOTB features to the Fullest by consuming this Classes and throwing the way it does , we can Briefly see how to handle it .

ATG 11.3 JAX-RS Implementation has inbuilt class RestException for handling this .  RestException  is the class that has different constructors for Providing the required inputs to be passed while Throwing it .

RestException error = RestUtils.getRestUtils().createException(400, "500", "Internal Server Error", null, null);

throw error;

Same like this above will have many constructors 

From the above example A RestException class can be instantiated
through utility methods in RestUtils , hence we are injecting in this way and supplying the parameters.

If you add error conditions to your endpoint, you should build a RestException, setting HTTP response codes,error messages, debug information and, optionally, error codes that are returned from your endpoint method.

400 is the status codes .

500 is the "internalserver" ie error codes

"Internal Server Error" is the message 

The RestExceptionMapper instance of the Jersey ExceptionMapper builds a response from the RestException that is returned to the client.If you want to handle any custom unhandled exceptions you can write the code here for handling it .


Additinally Every REST method should be constructed with an error message,which should be stored as resource strings in a property file residing in your custom module. Once you have constructed an error message, you can create string constants that refer to the error string keys within your endpoint class.


I am gives some of the status codes which you can use it while developing it .


ACCEPTED 202 Accepted
BAD_REQUEST 400 Bad Request
CONFLICT 409 Conflict
CREATED 201 Created
FORBIDDEN 403 Forbidden
GONE 410 Gone
INTERNAL_SERVER_ERROR 500 Internal Server Error
MOVED_PERMANENTLY 301 Moved Permanently
NO_CONTENT 204 No Content
NOT_ACCEPTABLE 406 Not Acceptable
NOT_FOUND 404 Not Found
NOT_MODIFIED 304 Not Modified
OK 200 OK
PRECONDITION_FAILED 412 Precondition Failed
SEE_OTHER 303 See Other
SERVICE_UNAVAILABLE 503 Service Unavailable
TEMPORARY_REDIRECT 307 Temporary Redirect
UNAUTHORIZED 401 Unauthorized
UNSUPPORTED_MEDIA_TYPE 415 Unsupported Media Type

It is our duty to set the correct status codes and error codes while throwing it .

Happy Handling !!!!


No comments:
Write comments