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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Trending

  • Customer 360: Fraud Detection in Fintech With PySpark and ML
  • Teradata Performance and Skew Prevention Tips
  • How AI Agents Are Transforming Enterprise Automation Architecture
  • How to Format Articles for DZone
  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.

By 
Roshan Thomas user avatar
Roshan Thomas
·
Feb. 18, 15 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
284.6K 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.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!