Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Exception Handling in Spring REST Web Service

DZone's Guide to

Exception Handling in Spring REST Web Service

Learn how to handle exception in Spring controller using: ResponseEntity and HttpStatus, @ResponseStatus on the custom exception class, and more custom methods.

· Integration Zone ·
Free Resource

Are your API program basics covered? Read the 5 Pillars of Full Lifecycle API Management eBook

There are a few different ways to handle exception in Spring controller.

  • Using ResponseEntity and HttpStatus codes
  • Using @ResponseStatus on the custom exception class
  • Using custom method to handle error on the controller(@ExceptionHandler and @ResponseStatus).
  • Return error representation instead of default html error page

Let’s start with a typical controller method in spring REST web service.

@RequestMapping(value="/customer/{id}" ,headers = "Accept=application/json","application/xml")
public Customer getCustomerById(@PathVariable String id)
{
Customer customer;
try 
{
customer = customerService.getCustomerDetail(id);
} 
catch (CustomerNotFoundException e) 
{

throw new RuntimeException(e);
}

return customer;
}

Here we are throwing a unchecked exception in the catch block of this method. This will give a default HttpStatus 500 error page. This doesn’t give any proper information to the client.

  • Using @ResponseEntity

Instead of HttpStatus 500 exception we can throw a HttpStatus 404 exception stating resource not found. In order to do this we need to ResponseEntity from the controller method. This ResponseEntity class takes two arguments, one is the returning object itself and other the status code.  But this adds more code into the controller method and makes it complex with all try catch blocks. Please see the code snippet below.

@RequestMapping(value="/customer/{id}" ,headers = "Accept=application/json","application/xml")
public ResponseEntity<Customer> getCustomerById(@PathVariable String id)
{
Customer customer;
try 
{
customer = customerService.getCustomerDetail(id);
} 
catch (CustomerNotFoundException e) 
{

return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
}

return new ResponseEntity<Customer>(customer,HttpStatus.OK);
}
  • Using @ResponseStatus

There is another way to handle this, using @ResponseStatus on the custom exception class. Here we have a custom exception class called CustomerNotFoundException. This annotation takes two arguments, one for value which defines the return HttpStatus code and another for reason, the custom messages which will be returned to the client. Please see the code snippet below.

@RequestMapping(value="/customer/{id}" )
public Customer getCustomerById(@PathVariable String id) throws CustomerNotFoundException
{
return customerService.getCustomerDetail(id);
}

Please see the custom exception class below

@ResponseStatus(value="HttpStatus.NOT_FOUND",reason"This customer is not found in the system")
public class CustomerNotFoundException extends Exception 
{
private static final long serialVersionUID = 100L;
}
  • Using @ExceptionHandler and @ResponseStatus

There is a third way to handle exception, using custom method to handle error on the controller. Here we use another exception @ExceptionHandler along with @ResponseStatus to map the exception to the custom method. Please see the code snippet.

@ResponseStatus(value="HttpStatus.NOT_FOUND",reason"This customer is not found in the system")
@ExceptionHandler(CustomerNotFoundException.class)
public void exceptionHandler() 
{

}
  • Return error representation instead of default html error page

One more thing we can add to this. Instead of sending back the regular html page, we can return error representation in json or xml format to the client. For that we can use the custom method we created to handle the exception. We can write a body for this method to return the error represention. In this cae we must remove the @ResponseStatus annotation from this method. Otherwise the spring will not process the method body. Please see the code snippet below.

@ExceptionHandler(CustomerNotFoundException.class)
public ResponseEntity<ClientErrorInformation> rulesForCustomerNotFound(HttpServletRequest req, Exception e) 
{
ClientErrorInformation error = new ClientErrorInformation(e.toString(), req.getRequestURI());
return new ResponseEntity<ClientErrorInformation>(error, HttpStatus.NOT_FOUND);

}
@RequestMapping(value="/customer/{id}" )
public Customer getCustomerById(@PathVariable String id) throws CustomerNotFoundException
{
return customerService.getCustomerDetail(id);
}

These are some of the ways to handle exception in a Spring MVC/REST based application.

Establish API creation, publishing and discovery as a master practice with the API Management Playbook.

Topics:
spring mvc ,integration ,rest ,web services

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}