DEV Community

realNameHidden
realNameHidden

Posted on

4 1 1 1 1

@ControllerAdvice and @ExceptionHandler Annotations Spring Boot

Exception Handling in Spring Boot — A Simple Example 🚀
Spring Boot provides multiple ways to handle exceptions gracefully. One of the best ways is to use @ControllerAdvice along with @ExceptionHandler to handle exceptions globally.

📌 Example: Handling Custom Exceptions in Spring Boot

Image description

1️⃣ Create a Custom Exception Class

package com.example.exceptionhandling.exception;

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

Enter fullscreen mode Exit fullscreen mode

This custom exception will be thrown when a requested resource is not found.

2️⃣ Create a Global Exception Handler

package com.example.exceptionhandling.handler;

import com.example.exceptionhandling.exception.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

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

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGlobalException(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Enter fullscreen mode Exit fullscreen mode

}
🔹 Explanation:
✅ @ControllerAdvice → Enables global exception handling across controllers.
✅ @ExceptionHandler(ResourceNotFoundException.class) → Handles ResourceNotFoundException.
✅ @ExceptionHandler(Exception.class) → Handles all other exceptions.

3️⃣ Create a REST Controller That Triggers an Exception

package com.example.exceptionhandling.controller;

import com.example.exceptionhandling.exception.ResourceNotFoundException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @GetMapping("/resource")
    public String getResource(@RequestParam String name) {
        if ("error".equalsIgnoreCase(name)) {
            throw new ResourceNotFoundException("Resource with name '" + name + "' not found");
        }
        return "Resource found: " + name;
    }
}

Enter fullscreen mode Exit fullscreen mode

}
🔹 How it Works?
If the user calls /resource?name=error, a ResourceNotFoundException is thrown.

The global exception handler catches it and returns an appropriate error response.

📌 Testing the API with Postman or Browser
✅ Valid Request

GET http://localhost:8080/resource?name=java
Response: 200 OK
Body: "Resource found: java"

Enter fullscreen mode Exit fullscreen mode

❌ Invalid Request (Triggers Exception)

GET http://localhost:8080/resource?name=error
Response: 404 Not Found
Body: "Resource with name 'error' not found"
Enter fullscreen mode Exit fullscreen mode
http://localhost:8080/resource?
Response: 500 Internal Server Error
Body: An Error occured: Required request parameter 'name' for method parameter type String is not present

Enter fullscreen mode Exit fullscreen mode

📌 Summary
✔ Custom Exception → Created ResourceNotFoundException.
✔ Global Exception Handling → Used @ControllerAdvice with @ExceptionHandler.
✔ REST Controller → Simulated an exception scenario.

Top comments (0)