简体   繁体   中英

Rest Exceptions: Wrappers vs Error Object

Lets say we have a rest service defined as:

    @GET
    @Produces("application/json")
    public Response getAllCategories(@QueryParam(value="startIndex") int startIndex, @QueryParam(value="size") int size)
    {

        logger.info("[SampleCategoryController][getAllCategories]");

        List<YpCategory> categoryList = sampleCategoryService.getAllCategories(startIndex, size);       
        return Response.ok(categoryList).build();       
    }

and the service is defined as:

public class SampleCategoriesServiceImpl {

    public List<YpCategory> getAllCategories(int startIndex, int size) {
        ...
        //call some method that throws a runtime exception
        ...

    }
}

And an Application Exception handler:

@Provider
@Component
public class ApplicationExceptionHandler implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable ex) {  
            String internalError = "There was a problem processing your request.";
            return Response.serverError().entity(new ExceptionResponse(500, internalError)).build();
        }
    }

 }

Exception response object : Let the exception bubble up to the ApplicationExceptionHandler and return the ExceptionResponse Object. This way seems cleaner because the service doesn't have to try to handle an exception that it can't really do anything with and the client will still receive a json response.

Response wrapper : The category object would extend some type of generic response wrapper object with information about error codes then I would always have to wrap the method that can throw a runtime exception in a try/catch block and set the error codes and message info in the catch block.

Is one of these ways preferred? Are there cons to using either one of these methods to handle errors?

I think you should use the ExceptionMapper in this case. It is cleaner to let exceptions be handled outside of your implementation. Also your implementation should be as less possible aware of HTTP. The less your implementation knows about the other parts of your framework the more flexible it will become.

To give an example. Lets say that in the future there is support for a non-HTTP protocol and error messaging will go different then using HTTP status code. You can do the implementation at the level of ExceptionMapper without changing your implementation. Otherwise you have to refactor your application to be aware of the non-HTTP protocol.

Just to be clear, I don't say there is an other implementation available now. It is just a theory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM