ExceptionHandler annotation

ExceptionHandler annotation

The `@ExceptionHandler` annotation in Spring is used to handle exceptions thrown by methods in a controller. It allows you to define methods that will be invoked when specific exceptions occur, enabling you to manage error responses and provide customized error handling.

ExceptionHandler annotation

Example

  • Step 1: Create a Spring Boot Application
    • Ensure you have the necessary dependencies in your `pom.xml` (for Maven) or `build.gradle` (for Gradle).

Maven Dependency
```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
```

Gradle Dependency
```groovy
implementation 'org.springframework.boot:spring-boot-starter-web'
```

  • Step 2: Create the Main Application Class
    • Create the main class for the Spring Boot application.

Example
```java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
```

Explanation:

  • `@SpringBootApplication`: Indicates a configuration class that declares one or more `@Bean` methods and also triggers auto-configuration and component scanning.

  • Step 3: Create a Custom Exception
    • Define a custom exception class.

Example
```java
package com.example.demo.exception;

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}
```

Explanation:

  • `UserNotFoundException`: A custom exception that extends `RuntimeException` to represent a specific type of error.

  • Step 4: Create a Controller
    • Create a controller class that may throw exceptions and has an `@ExceptionHandler` method to handle them.

Example
```java
package com.example.demo.controller;

import com.example.demo.exception.UserNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping("/users/{id}")
    public String getUser(@PathVariable("id") Long id) {
        if (id <= 0) {
            throw new UserNotFoundException("User with ID " + id + " not found.");
        }
        return "User ID: " + id;
    }

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}
```

Explanation:

  • `@RestController`: Indicates that this class is a REST controller, and the return values of methods are directly written to the HTTP response body.
  • `@RequestMapping(“/api”)`: Specifies that all methods in this class handle requests starting with `/api`.
  • `@GetMapping(“/users/{id}”)`: Maps GET requests to `/api/users/{id}` to the `getUser` method.
  • `@PathVariable(“id”)`: Binds the `{id}` path variable from the URL to the `id` method parameter.
  • `@ExceptionHandler(UserNotFoundException.class)`: Defines a method to handle `UserNotFoundException`. This method will be invoked when the specified exception is thrown.
  • `handleUserNotFoundException`: Returns a `ResponseEntity` with the exception message and an HTTP status of `404 Not Found`.

  • Step 5: Running the Application
    • Run the application from the main class (`DemoApplication`). You can test the endpoint using a tool like Postman or by navigating to the URL in your browser:
  • GET request to `http://localhost:8080/api/users/0` should return a `404 Not Found` status with the message `”User with ID 0 not found.”`.

Conclusion

  • `@ExceptionHandler`: Used to handle exceptions thrown by controller methods. It allows for customized error handling and response management.
  • Example: Demonstrated how to use `@ExceptionHandler` to manage exceptions in a Spring Boot controller and return appropriate error responses.