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.
Join the DZone community and get the full member experience.
Join For FreeThere are a few different ways to handle an exception in Spring controller.
- Using
ResponseEntity
andHttpStatus
codes - Using
@ResponseStatus
on the custom exception class - Using a custom method to handle error on the controller (
@ExceptionHandler
and@ResponseStatus
). - Return error representation instead of the 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 an 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 a HttpStatus 500 exception, we can throw a HttpStatus 404 exception stating the resource not found. In order to do this, we need to use 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 an exception, using a 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 case, 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 an exception in a Spring MVC/REST based application.
Opinions expressed by DZone contributors are their own.
Comments