How to handle Exceptions in Realtime Project with Spring?

Опубликовано: 10 Май 2026
на канале: Tausief S
286
9

In Spring Boot, you can use @ControllerAdvice to handle exceptions globally across your application. @ControllerAdvice allows you to define centralized exception handling logic that will be applied to multiple controllers or throughout your entire application. This can help you provide consistent error handling and responses.

Here's a step-by-step guide on how to use @ControllerAdvice to handle exceptions in Spring Boot:

Create a Global Exception Handling Class:
Create a new class annotated with @ControllerAdvice. This class will contain methods to handle various types of exceptions.

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

// Define exception handling methods here
}


Create Exception Handling Methods:
Inside the GlobalExceptionHandler class, create methods annotated with @ExceptionHandler to handle specific exception types. You can handle different exceptions and customize the response for each one.

@ExceptionHandler(NotFoundException.class)
public ResponseEntity handleNotFoundException(NotFoundException ex) {
// Customize the response for NotFoundException
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}

@ExceptionHandler(BadRequestException.class)
public ResponseEntity handleBadRequestException(BadRequestException ex) {
// Customize the response for BadRequestException
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}

// You can add more exception handling methods as needed

In the example above, we handle NotFoundException and BadRequestException exceptions and return customized responses for each.

Define Custom Exception Classes:
You should define your custom exception classes that extend RuntimeException or a more specific exception class if appropriate. For example:

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

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

Trigger Exceptions:
In your controller methods, you can throw these custom exceptions when needed. For instance:

User user = userRepository.findById(id)
.orElseThrow(() -] new NotFoundException("User not found with ID: " + id));

Here, if a user with the specified ID is not found, a NotFoundException will be thrown.

Testing:
Test your exception handling by invoking the endpoints that may trigger exceptions. Verify that the responses are customized according to your exception handling logic.

With @ControllerAdvice, you can centralize exception handling in your Spring Boot application, making your code cleaner and more maintainable while providing consistent error responses to clients.