Understanding @ControllerAdvice in Spring Boot
Spring Boot makes it easier to build web applications with useful features like automatic configuration and easy handling of requests. One of these helpful features is @ControllerAdvice. In this blog post, we will explain what @ControllerAdvice is, how it works, and how to use it in your Spring Boot applications.
What is @ControllerAdvice?
@ControllerAdvice is an annotation in Spring Boot that allows you to handle exceptions, add common data to the model, and apply other configurations across all controllers in your application. It works like a helper for managing your controllers without repeating code in each one.
In simple words, @ControllerAdvice helps you handle errors and manage data in a centralized way for all your controllers. It can be used to:
Let’s take a closer look at how to use @ControllerAdvice in your Spring Boot application.
Why Should You Use @ControllerAdvice?
How to Use @ControllerAdvice in Spring Boot
To use @ControllerAdvice, follow these steps:
Example: Basic @ControllerAdvice Usage
Let’s say you want to handle a custom exception called ResourceNotFoundException globally and return a meaningful error message. Here’s how to do it.
Step 1: Define a Custom Exception
First, create a custom exception class.
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
Step 2: Create the @ControllerAdvice Class
Now, create a @ControllerAdvice class to handle this exception.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class GlobalExceptionHandler {
// Handle ResourceNotFoundException globally
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
// Add common attribute to the model for all controllers
@ModelAttribute
public void addCommonAttributes(Model model) {
model.addAttribute("appName", "My Spring Boot Application");
}
}
Step 3: Throw the Exception in a Controller
Now, create a controller where you will throw the ResourceNotFoundException when a resource is not found.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/resource/{id}")
public String getResourceById(@PathVariable String id) {
if ("123".equals(id)) {
return "Resource found!";
} else {
throw new ResourceNotFoundException("Resource not found with id: " + id);
}
}
}
How It Works:
Conclusion
@ControllerAdvice is a helpful feature in Spring Boot that allows you to handle exceptions, add common data, and configure global settings for your controllers. By using @ControllerAdvice, you can avoid repeating code, improve the readability of your application, and provide better error handling. Whether you are building a web application or an API, @ControllerAdvice will help make your code more efficient and easier to maintain.
Software Engineer MERN | React.JS | Nodejs | Javascript | Typescript | MongoDB | GCP | Python
5 天前Very nice
Fullstack Engineer | Software Developer | React | Next.js | TypeScript | Node.js | JavaScript | AWS
6 天前Very informative
Senior Software Engineer | Backend-Focused Fullstack Developer | .NET | C# | Angular | React.js | TypeScript | JavaScript | Azure | SQL Server
6 天前Thanks for sharing JUNIOR NAKAMURA
Senior Fullstack Developer | Java, Angular & React Specialist | Oracle & AWS Certified
6 天前Strong insight!!
Senior QA Automation Engineer | SDET | Java | Selenium | Rest Assured | Robot Framework | Cypress | Appium
6 天前Very informative