🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
The @ExceptionHandler annotation in Spring Boot is used within a controller to handle specific types of exceptions thrown by request-handling methods. This annotation helps in managing exceptions locally within a controller or globally across multiple controllers when used with @ControllerAdvice.
Key Points
1. @ExceptionHandler is used to define methods to handle exceptions thrown in associated controllers.
2. This annotation allows for clean exception handling by mapping specific exceptions to specific handler methods.
3. Custom exceptions can be defined and handled to cater to specific business logic errors.
2. Development Steps
1. Define custom exceptions.
2. Create a controller with methods that might throw these exceptions.
3. Use @ExceptionHandler to handle these exceptions within the controller.
3. Implementation
// Step 1: Define custom exceptions
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
public class InvalidRequestException extends RuntimeException {
public InvalidRequestException(String message) {
super(message);
}
}
// Step 2: Create a controller with methods that throw exceptions
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
@RestController
public class MyController {
@GetMapping("/resource/{id}")
public String getResource(@PathVariable String id) {
if(id.equals("0")) {
throw new ResourceNotFoundException("Resource not found for ID: " + id);
}
return "Resource data for ID: " + id;
}
@GetMapping("/validate/{number}")
public String validateNumber(@PathVariable int number) {
if(number <= 0) {
throw new InvalidRequestException("Invalid number: " + number);
}
return "Valid number: " + number;
}
}
// Step 3: Use @ExceptionHandler to handle exceptions in the controller
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestController
public class ExceptionHandlingController {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(InvalidRequestException.class)
public ResponseEntity<String> handleInvalidRequestException(InvalidRequestException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
}
Explanation:
1. Custom exceptions ResourceNotFoundException and InvalidRequestException are defined to handle specific conditions like missing resources or invalid inputs.
2. MyController includes methods that throw these custom exceptions under certain conditions, demonstrating their use within typical business logic.
3. ExceptionHandlingController includes @ExceptionHandler methods that specifically handle the custom exceptions thrown by MyController. These handlers ensure that appropriate HTTP responses are returned to the client, indicating the nature of the error encountered.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment