EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot Exception Handling
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring boot grpc
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot Exception Handling

Spring Boot Exception Handling

Introduction to Spring Boot Exception Handling

The following article provides an outline for Spring Boot Exception Handling. In spring boot, we have a mechanism to handle the exceptions globally by the use of controller advice provided by the spring boot framework. We should properly handle the exception and error, if any, in the API because, by that, we can return a useful status code to the client when the request for a particular resource from the server, also; we may get several exceptions while performing any business logic so we should handle them properly.

We should try to give some useful message to the client from which they can understand because they cannot understand the technical issue. We have class-based annotation and method based annotation in spring boot two handle the exceptions in our application. Here in this tutorial, we will see how we can implement this on our spring boot application to get useful information and status code if an exception occurs.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Spring Boot Exception Handling

In spring, we can handle them globally; we have to use the standard annotation provided by the spring boot framework.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,130 ratings)

@ControllerAdvice
public class Name_of_class {
}

As you can see, we can create one class and annotate it using @ControllerAdvice in spring boot.

Example:

@ControllerAdvice
public class MyExceptionnHandler {
// logic will go here .. //
}

As you can see in the above piece of syntax, we can now write and handle our custom exception for the application.

How does Exception Handling work in Spring Boot?

As now we already know that exception handling can be done globally in spring boot, means we can have one class which can handle all the exception of the application at one place. In spring boot, we have @ControllerAdvice, which is responsible for handling the exception globally in spring boot. Also, we have one more annotation, which we have not talked about since this far, which is @ExceptionHandler, this annotation is responsible for handling the particular exception, and we used this to send the response to the client.

Here we will see how we can use both of this to create the custom exception handler in spring-boot:

1. @ExceptionHandler

This annotation can be used to handle the exception at the controller level. By the use of it, we can annotate a method with this, and it will be responsible for handling the exception if it occurs at this controller only. So by the use of it, we have to write the same method on every controller; this is not globally for our while application; this is easy to use, implement and handle but not feasible.

Example:

public class DemoController{
@ExceptionHandler({ yourexceptionclass1.class, yourexceptionclass2.class , ...soon})
public void handleexception() {
// logic will go here ..//
}
}

As you can see in the above code, we have defined one method which is going to handle the exception for our application. Inside that handler annotation, we can pass our all the custom class that we have created. This seems simple but not good practice to handle the exception globally in the application.

2. @ControllerAdvice

Spring boot provides us controller advice which is responsible for handling the exception at a global level. We have to just use this annotation and create one class, which will handle the multiple customs create exception at one level only.

Below are some advantages of using this to handle the exception:

  • By the use of it, we can easily set the response message and Http status code by the use of ResponseEntity.
  • We can define any number of exception handlers in this class, which will be global and used anywhere.

We have seen two approaches, but then we will see steps to implement the second one because it is more flexible to use without repeating the same code.

Let’s see the implementation of the second approach.

a. We have to first create the spring boot application from scratch if you do not have one. Go to spring initializer and fill in the details as per your need.

b. Generate the zip and import the project into your favorite editor; now, let get started with the actual implementation.

c. Now, we have to create one controller advice which will contain all the exception handler at a single level for our application; for this, we have to have proper import statement and packages in place.

Below is the syntax for the controller advice class:

Example:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ControllerAdvice
public class EmployeeExceptionController {
@ExceptionHandler(value = EmployeeNotExixts.class)
public ResponseEntity<Object> exception(EmployeeNotExixts exception) {
return new ResponseEntity<>("Employee do notexists !!", HttpStatus.NOT_FOUND);
}
}

d. Now, we have to create our custom exception that we have defined above in the controller advice class, i.e. ‘EmployeeNotExixts’.

Below is the syntax for the custom exception class:

Example:

public class EmployeeNotExixts extends RuntimeException {
private static final long serialVersionUID = 1L;
}

This class should extend the RuntimeException in order to throw any unchecked exception from the application.

e. Now, we need one controller to test our exception handling in the spring boot application; for this, we will write one method which is going to find the employee from the database based on the id passed in URL.

Example:

@RestController
@CrossOrigin
@RequestMapping("/operations/")
public class ActionController {
@RequestMapping(value = "get/employee/{id}", method = RequestMethod.GET)
public ResponseEntity<Object> getEmployee(@PathVariable("empid") Long empid) {
// db call to fetch the emp and check ..///
if(!empid)throw new EmployeeNotExixts();
// logic goes here if emp found ..//
return new ResponseEntity<>("Found", HttpStatus.OK);
}
}

Now here we are trying to fetch the employee based on the id; if not found, we will throw employee not found exception in return to the client with HTTP status code and response message as well.

f. Main class for spring boot application will be plain and simple like always.

Example:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.*;
@SpringBootApplication
public class EmployeeApplication {
public static void main(String[] args)
{
SpringApplication.run(EmployeeApplication.class, args);
}
}

Output:

Spring Boot Exception Handling

Conclusion

As you can see, exception handling is very easy to implement in the spring boot framework because it provides us good support to make it global and used anywhere in the any controller whenever we want, without being repeat the code as well.

Recommended Articles

This is a guide to Spring Boot Exception Handling. Here we discuss the introduction and how exception handling works in spring boot? You may also have a look at the following articles to learn more –

  1. Maven Repository Spring
  2. Spring Boot DevTools
  3. Spring AOP
  4. Spring Cloud Components
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

Special Offer - Spring Boot Training Program (2 Courses, 3 Project) Learn More