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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Aggregating REST APIs Calls Using Apache Camel

Trending

  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Ethical AI in Agile
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • MCP Servers: The Technical Debt That Is Coming
  1. DZone
  2. Coding
  3. Frameworks
  4. Global Exception Handling Using Spring @RestControllerAdvice in REST Services

Global Exception Handling Using Spring @RestControllerAdvice in REST Services

This article will try to cover global exception handling using ControllerAdvise annotation introduced in Spring 4.3.

By 
Dharmendra Rathor user avatar
Dharmendra Rathor
·
Jan. 15, 20 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
64.3K Views

Join the DZone community and get the full member experience.

Join For Free

golden retriever sleeping in sunlight

A REST API developer will have two requirements related to error handling.

  1. Common place for Error handling
  2. Similar Error Response body with a proper HTTP status code across APIs

Both requirements can be addressed by using RestControllerAdvice annotation in Spring.

Refer to code at https://github.com/DharmendraRathor/springzone/tree/master/customer.

I have created Get customer service for customer resource.

Java
x
13
 
1
@RestController
2
@RequestMapping("/customer")
3
public class CustomerController {
4
 
          
5
    @Autowired
6
    private CustomerManager customerManager;
7
 
          
8
    @GetMapping("/{id}")
9
    public Customer getCustomer(@PathVariable String id) {
10
        return customerManager.getCustomer(id).orElseThrow(() -> new NotFoundException("Customer not found with id " + id));
11
    }
12
 
          
13
}


curl --request GET --url http://localhost:8080/customer/1

Java
xxxxxxxxxx
1
 
1
If customer does not exist in DB , I want to throw error message with http Status 404.
2
 
          
3
{
4
  "errorCode": "NOT_FOUND_ERROR",
5
  "errorMsg": "Customer not found with id 1",
6
  "status": 404,
7
  "timestamp": "2019-12-26 11:45:59"
8
}
9
 
          


To achieve this, we have to define global exception handler class with annotation @RestControllerAdvice.

You may also be interested in:  Global Exception Handling With @ControllerAdvice

We have added one method "handleGenericNotFoundException", which handles exceptions defined with

@ExceptionHandler(value = NotFoundException.class).

Any service generating exception "NotFoundException" will come to “handleGenericNotFoundException” method, and the method will wrap the exception in common format using the "CustomErrorResponse" class. In this case, the "customer not found" error will be thrown as defined in “handleGenericNotFoundException” method inside the ExceptionAdvice class.

Java
xxxxxxxxxx
1
12
 
1
@RestControllerAdvice
2
public class ExceptionAdvice {
3
 
          
4
    @ExceptionHandler(value = NotFoundException.class)
5
    public ResponseEntity<CustomErrorResponse> handleGenericNotFoundException(NotFoundException e) {
6
        CustomErrorResponse error = new CustomErrorResponse("NOT_FOUND_ERROR", e.getMessage());
7
        error.setTimestamp(LocalDateTime.now());
8
        error.setStatus((HttpStatus.NOT_FOUND.value()));
9
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
10
    }   
11
 
          
12
}


CustomErrorResponse can be found at CustomErrorResponse.

We can define multiple error handler methods for different types of exceptions generated by services in "ExceptionAdvice" class and wrap each using common CustomErrorResponse response. This will make sure we have common place to handle errors and all services return similar error responses.

The git repo for the complete project git project.


Further Reading

Spring REST Service Exception Handling

How to Deal With Exceptions

REST Web Protocols Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Aggregating REST APIs Calls Using Apache Camel

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!