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
1οΈβ£ Create a Custom Exception Class
package com.example.exceptionhandling.exception;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
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);
}
}
}
πΉ 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;
}
}
}
πΉ 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"
β Invalid Request (Triggers Exception)
GET http://localhost:8080/resource?name=error
Response: 404 Not Found
Body: "Resource with name 'error' not found"
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
π Summary
β Custom Exception β Created ResourceNotFoundException.
β Global Exception Handling β Used @ControllerAdvice with @ExceptionHandler.
β REST Controller β Simulated an exception scenario.
Top comments (0)