Rest Restres service exception: best way to handle

I have a holiday service that will throw an exception, and I want to know what would be the best way to handle this.

So, I have a recreation service that can throw a user-defined exception and I will catch this inside the catch block and throw that exception again! and use the rest system to catch it. Similarly for exceptions not defined by the user. I thought it would be good, since I have a number of services for recreation, and all the processing of the code using userdefinedexception will be in one place.

I would like to know if this is the right way to handle exceptions in the leisure service?

I use a T-shirt.

 // rest service 
 @POST
 public void doSomething () {

 try {
 // ... some piece of code that can throw user defined exception as well as runtime exception
 } catch (UserDefinedException e) {
 throws new UserDefinedException (e);
 } catch (Exception e) {
 throws new ServiceException (e);
 } 

 // Now I have a @Provider to catch this thrown exception 

 @Provider
 public class UserDefinedExceptionHandler implements
         ExceptionMapper {

     public Response toResponse (UserDefinedException exception) {
         ClientResponse clientResponse = new ClientResponse ();
         ResponseStatus status = new ResponseStatus ();

         clientResponse = handleUserDefinedException (exception, status, clientResponse);

         return Response.ok (clientResponse) .build ();
     }

 // similarly for the ServiceException
+4
source share
2 answers

Simply raising the 500 error on the server does not give detailed error information; one way to gracefully handle errors is to wrap the response data in the structure with status and data, if the state is an error, show the correct message.

something like this in json format:

{ "status": "error", "data": { "message": "detailed error message" } } 
+5
source

Exception handling in the REST service is not much different from exception handling in any other piece of code.

The only β€œconvention” is to drop HTTP 400 if the exception is thrown by the client sending the wrong data, and 500 when your service unexpectedly fails.

+1
source

All Articles