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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

  • RAG Done Right: When to Use SQL, Search, and Vector Retrieval and How To Combine Them
  • Putting Guardrails Around What Your AI Agent Is Allowed to Touch
  • How to Test PUT, PATCH, and DELETE API Requests Using Playwright TypeScript
  • How to Format Articles for DZone

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
285.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 🔴 Hot News: articles/exception handling spring rest - Kapook Update 2025
  • 🔴 Hot News: articles/exception handling spring rest - Kapook Update 2025
  • 🔴 Hot News: articles/exception handling spring rest - Kapook Update 2025

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • 🔴 Hot News: articles/exception handling spring rest - Kapook Update 2025
  • 🔴 Hot News: articles/exception handling spring rest - Kapook Update 2025
  • 🔴 Hot News: articles/exception handling spring rest - Kapook Update 2025