DEV Community

realNameHidden
realNameHidden

Posted on

5 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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Tiger Data image

🐯 πŸš€ Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

πŸ‘‹ Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s dayβ€”leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay