Reporting errors using application exceptions

It is recommended to use a checked application exception for recoverable error scenarios. In this section, we will see how a checked exception can be used in a RESTful web API implementation.

Here is a checked business exception definition for use in the JAX-RS resource method:

//Business exception class 
public class DeprtmentNotFoundBusinessException extends Exception{ 
 
    public DeprtmentNotFoundBusinessException(String message) { 
        super(message); 
    } 
 
    public DeprtmentNotFoundBusinessException(String message,  
       Throwable cause) { 
        super(message, cause); 
    } 
 
    //Rest of the implementation code goes here 
} 

The following code snippet uses DeprtmentNotFoundBusinessException for reporting the DepartmentNotFound error to the caller:

@DELETE 
@Path("departments/{id}") 
public void remove(@PathParam("id") Short id) throws  
    DeprtmentNotFoundBusinessException { 
    //Read department from data store for id 
    Department department = findDepartmentEntity(id); 
    // throw exception if department to be deleted is not found 
    if(department == null){ 
        throw new DeprtmentNotFoundBusinessException 
            ("Department is missing in store"); 
 
    } 
    removeDepartmentEntity(department); 
} 

The preceding implementation is simple and easy to follow. However, you may want to perform an additional step to map exceptions to the HTTP response body content. Note that the JAX-RS runtime, by default, does not know how to generate the right response content for the custom application exception thrown by a method. All the unhandled exceptions are handled by the underlying servlet container, which may wrap or swallow your application exception. The solution is to use the exception mapper feature offered by JAX-RS. JAX-RS allows you to deploy a custom exception mapper implementation, which will map the business exception to the appropriate response message. The next section discusses this topic in detail.

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

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