0
0
Spring Bootframework~30 mins

@ControllerAdvice for global handling in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Global Exception Handling with @ControllerAdvice in Spring Boot
📖 Scenario: You are building a simple Spring Boot web application that manages user data. You want to handle errors like missing users or invalid input in one place, so your app shows friendly error messages everywhere.
🎯 Goal: Create a global error handler using @ControllerAdvice that catches exceptions from all controllers and returns a clear error message with HTTP status.
📋 What You'll Learn
Create a custom exception class called UserNotFoundException.
Create a controller class called UserController with a method to get a user by ID.
Create a global exception handler class annotated with @ControllerAdvice.
Add a method in the global handler to catch UserNotFoundException and return a ResponseEntity with status 404 and a message.
💡 Why This Matters
🌍 Real World
Global exception handling helps keep your web app clean and user-friendly by managing errors in one place instead of repeating code in every controller.
💼 Career
Understanding @ControllerAdvice and global error handling is essential for backend developers working with Spring Boot to build robust and maintainable web services.
Progress0 / 4 steps
1
Create the UserNotFoundException class
Create a public class called UserNotFoundException that extends RuntimeException. Add a constructor that accepts a String message and passes it to the superclass constructor.
Spring Boot
Need a hint?

Think of this class as a special error you create when a user is not found.

2
Create UserController with a method to get user by ID
Create a class called UserController annotated with @RestController. Add a method getUserById that takes a Long id as a path variable. Inside the method, throw new UserNotFoundException("User not found").
Spring Boot
Need a hint?

This controller simulates looking for a user but always throws the custom exception.

3
Create a global exception handler with @ControllerAdvice
Create a class called GlobalExceptionHandler annotated with @ControllerAdvice. Add a method handleUserNotFoundException annotated with @ExceptionHandler(UserNotFoundException.class) that takes a UserNotFoundException ex parameter and returns a ResponseEntity<String> with the exception message and HTTP status NOT_FOUND.
Spring Boot
Need a hint?

This class catches the custom exception from any controller and sends a 404 response with the message.

4
Complete the global handler with @ResponseBody annotation
Add the @ResponseBody annotation to the handleUserNotFoundException method in GlobalExceptionHandler to ensure the message is sent as the HTTP response body.
Spring Boot
Need a hint?

This annotation tells Spring to send the returned string as the response content.