This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Centralized Exception Handling in Spring Boot

  • Spring Boot
  • October 18, 2024

Share On :

Introduction 

Exception handling is essential for managing runtime errors, allowing developers to respond smoothly to unexpected issues. However, managing exceptions in large Spring Boot applications can become complicated if each controller or service handles them separately. This blog will discuss how to use @ControllerAdvice and @ExceptionHandler to master global exception handling, making your application simpler, easier to manage, and more efficient.

Prerequisites 
  • JDK 11 or later
  • Maven or Gradle
  • Spring Boot Development Environment (here IntelliJ IDEA)
What is global exception handling in spring boot 

In Spring Boot, global exception handling allows us to manage errors for the entire application from one central place, instead of handling exceptions in each controller or method separately. This approach makes your code cleaner and ensures consistent error responses.

Global exception handling in Spring Boot offers several benefits, including

  • Improved user experience
    • A consistent strategy for error management helps maintain a seamless user experience.
  • Easier code maintenance
  • Centralized exception-handling logic makes it easier to update error-handling strategies without modifying multiple places in the codebase.

Spring Boot provides two main tools for global exception handling

  • @ControllerAdvice is an annotation in Spring Boot that defines a global exception handler. It allows you to manage exceptions for all controllers in a centralized manner, making error handling more efficient and keeping your code clean and organized.
  • @ExceptionHandler is an annotation used within a @ControllerAdvice class to define methods that handle specific exceptions. It allows you to create custom responses for different types of exceptions that occur in your Spring Boot application.
Global Exception Resource not found
Why Use a Global Exception Handler 

A global exception handler in Spring Boot offers several key benefits:

    1. Centralized management: This enables you to handle exceptions from a single location, improving error handling and reducing redundancy.
    2. Clean Code: Separating error-handling logic from business logic, allows you to keep your code clean and maintainable by focusing on the critical functionality of the application.
    3. Consistent error response: A global handler ensures a uniform error response process, making it easier for customers to understand and address errors.
    4. Improved Debugging: Centralizing exception handling facilitates better logging and error tracking, aiding in the identification of issues.
    5. Flexible Response Handling: You can define custom responses for different exceptions, enhancing user communication and improving the user experience.
    6. Reduced Duplication: By centralizing error-handling behavior, you avoid code duplication across controllers, simplifying maintenance and updates.
Implementing Global Exception Handling   

In this example, we will create a simple Spring Boot application for managing employees, implementing global exception handling to ensure that any errors are handled consistently across the application.

Project Structure

Controller : Handles incoming requests.

Service : Contains business logic.

Repository : Interacts with the database.

Model : Defines the data structure.

Exception : Contains custom exceptions.

Common : Contains response format.

Step 1 : Add Dependencies (Configuration)

Before implementing any logic, ensure you have the necessary dependencies for Spring Boot, validation, and JPA in your pom.xml

				
					<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>


				
			

These dependencies are essential for

  • Web : Building RESTful APIs.
  • JPA : Interacting with the database.
  • Validation : Handling field-level validation, such as in your Employee entity.
  • Test : For writing unit and integration tests.

Step 2 : Create the Employee Model

This class represents the employee entity and contains validation annotations to ensure the integrity of the data.

				
					@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Employee {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long employeeId;

  @NotNull(message = "Invalid Name: Name is NULL")
  @Pattern(regexp = "^[A-Za-z0-9 ]*$", message = "Please enter only string")
  private String employeeName;

  @Email(message = "Invalid email")
  @NotNull(message = "Email cannot be NULL")
  private String email;

  @Pattern(regexp = "^\\d{10}$", message = "Invalid phone number")
  @NotNull(message = "Invalid Phone number: Number is NULL")
  private String phoneNumber;
}


				
			

Step 3 : Create the Employee Repository

This interface extends JpaRepository to provide CRUD operations for the Employee entity.

				
					@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
				
			

Step 4 : Create the Employee Service

In the Employee service class, we will write a business logic for managing employees and also handle some runtime exceptions. This class includes methods of adding employee data, retrieving employee data, updating employee data, and deleting employees from the table. Additionally, we will handle exceptions to ensure our application can handle instances where an employee does not exist in the table.

				
					@Service
public class EmployeeServiceImpl implements EmployeeService {

  private final EmployeeRepository employeeRepository;

  public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
    this.employeeRepository = employeeRepository;
  }

  @Override
  public Employee addEmployee(Employee employee) {
    return employeeRepository.save(employee);
  }

  @Override
  public List<Employee> getEmployee() {
    return employeeRepository.findAll();
  }

  @Override
  public void deleteEmployee(Long employeeId) {
// Throws ResourceNotFound exception if the employee does not exist
    Employee existEmployeeId = employeeRepository.findById(employeeId).orElseThrow(() ->
        new ResourceNotFound("Employee not Exists in id : " + employeeId));
    if(existEmployeeId!= null){
      employeeRepository.deleteById(employeeId);
    }
  }

  @Override
  public Employee updateEmployee(Long employeeId, Employee employee) {
// Throws ResourceNotFound exception if the employee does not exist
    Employee existEmployee = employeeRepository.findById(employeeId).orElseThrow(() ->
        new ResourceNotFound("Employee not Exists in id : " + employeeId));
    employee.setEmployeeName(existEmployee.getEmployeeName());
    employee.setEmail(existEmployee.getEmail());
    employee.setPhoneNumber(existEmployee.getPhoneNumber());
    return employeeRepository.save(existEmployee);
  }
}


				
			

Step 5 : Create the Employee Controller

This class handles incoming requests and returns responses. It communicates with the service layer and implements the error handling logic.

				
					@RestController
@RequestMapping("/employee")
public class EmployeeController {

  private final EmployeeServiceImpl employeeService;

  public EmployeeController(EmployeeServiceImpl employeeService) {
    this.employeeService = employeeService;
  }

  @PostMapping("/add")
  public ResponseEntity<Response> add(@Valid @RequestBody Employee employee){
    try{
      employeeService.addEmployee(employee);
      return new ResponseEntity<>(new Response("Employee added Successfully",Boolean.TRUE),
          HttpStatus.CREATED);
    }catch (Exception e){
      return new ResponseEntity<>(new Response(e.getMessage(),Boolean.FALSE),HttpStatus.BAD_REQUEST);
    }
  }

  @GetMapping("/get")
  public ResponseEntity<Response> get(){
    try{
      employeeService.getEmployee();
      return new ResponseEntity<>(new Response("Employees",Boolean.TRUE),
          HttpStatus.OK);
    }catch (Exception e){
      return new ResponseEntity<>(new Response(e.getMessage(),Boolean.FALSE),HttpStatus.BAD_REQUEST);
    }
  }

  @DeleteMapping("/delete/{id}")
  public ResponseEntity<Response> delete(@PathVariable("id") Long employeeId){
    try{
      employeeService.deleteEmployee(employeeId);
      return new ResponseEntity<>(new Response("Employees deleted successfully",Boolean.TRUE),
          HttpStatus.OK);
    }catch (Exception e){
      return new ResponseEntity<>(new Response(e.getMessage(),Boolean.FALSE),HttpStatus.BAD_REQUEST);
    }
  }

  @PutMapping("/update/{id}")
  public ResponseEntity<Response> update(@PathVariable("id") Long employeeId,Employee employee){
    try{
      employeeService.updateEmployee(employeeId,employee);
      return new ResponseEntity<>(new Response("Employees updated successfully",Boolean.TRUE),
          HttpStatus.OK);
    }catch (Exception e){
      return new ResponseEntity<>(new Response(e.getMessage(),Boolean.FALSE),HttpStatus.BAD_REQUEST);
    }
  }
}


				
			

Step 6 : Create the Global Exception Handler

This class is responsible for handling exceptions globally. It will capture and respond to any exceptions thrown in the application.

				
					@RestControllerAdvice
public class GlobalExceptionHandler {

  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler({MethodArgumentNotValidException.class})
  public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException exception) {
    Map<String, String> errorMap = new HashMap<>();
    exception.getBindingResult().getFieldErrors()
        .forEach(error -> errorMap.put(error.getField(), error.getDefaultMessage()));
    return errorMap;
  }

  @ExceptionHandler(ResourceNotFound.class)
  public ResponseEntity<Response> handleResourceNotFound(ResourceNotFound ex) {
    Response response = new Response(ex.getMessage(), false);
    return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
  }
}


				
			

Step 7 : Create the Custom Exception

This class represents a custom exception that will be thrown when a requested resource is not found.

				
					public class ResourceNotFound extends RuntimeException{
  public ResourceNotFound(String message) {
    super(message);
  }
}
				
			

Step 8 : Create a Common Response Class

This class is used to standardize responses throughout the application, making it easier for clients to handle responses.

				
					@Data
public class Response {
    private String message;
    private Boolean status;

    public Response(String message, Boolean status) {
        this.message = message;
        this.status = status;
    }
}


				
			
Handling a Exception

By implementing global exception handling, we ensure that our application provides clear and consistent error messages. For example:

  1. Validation Errors : If the user enters invalid data, such as entering only their name rather than any combination of string and number, entering an email with incorrect format, entering a phone number as a mixture of string and number, and failing to enter 10 numbers, it will display a message and handle the exception using the Global exception.Example:
PostAPI User
  1. Resource Not Found : If a user tries to access a non-existent employee, the response will look like this
image12 (1)
Conclusion

In this blog, we showed how to handle users entering invalid inputs and runtime exceptions. We can handle all types of exceptions using a global exception handler class, and also we can create custom exception classes to handle runtime exceptions and make applications more efficient and user-friendly without breaking any functionality.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our Spring Boot services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

June 6, 2024
CRUD Restful APIs with Spring Boot
CRUD Restful APIs with Spring Boot
Loading...

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram