Spring Boot @ExceptionHandler Example

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.

Comments