Reporting errors using ResponseBuilder

 The Response instance can hold metadata, such as the HTTP status code, along with the entity body. The REST resource method can return the Response object to report back on the status of the REST API call to the caller.

For example, the following resource method returns HTTP 404 Not Found (represented by the following Enum constant: Response.Status.NOT_FOUND) if the department entity object is not found in the data store:

@DELETE 
@Path("departments/{id}") 
public Response remove(@PathParam("id") Short id) { 
    Department department = entityManager.find(Department.class, 
        id); 
    if(department == null){ 
        //Department to be removed is not found in data store 
        return Response.status(Response.Status.NOT_FOUND).entity 
            ("Entity not found for : " + id).build();  
    } 
    entityManager.remove(entityManager.merge(department)); 
    return  Response.status(Response.Status.OK).build(); 
} 

Although the approach of using the Response object for reporting errors back to the caller works for basic use cases, it may not really scale up in real life. With this approach, every resource method in a class should have the Response object as the return type. Furthermore, developers may need to catch all exceptions in the resource method and convert them to the Response object programmatically. This may eventually result in repetitive coding, silly coding errors, and maintenance issues. JAX-RS addresses this issue by allowing you to directly throw exceptions from the REST resource methods to report errors back to the caller. This model is explained in the next two sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.59