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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

If you found this article helpful, a little ❀️ or a friendly comment would be much appreciated!

Got it