DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Exception Handling in Spring REST Web Service

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.

Roshan Thomas user avatar by
Roshan Thomas
·
Feb. 18, 15 · Tutorial
Like (13)
Save
Tweet
Share
281.36K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Using ResponseEntity and HttpStatus 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.

REST Web Protocols Web Service Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Building a Real-Time App With Spring Boot, Cassandra, Pulsar, React, and Hilla
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Spring Boot, Quarkus, or Micronaut?
  • Real-Time Analytics for IoT

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: