0
0
SpringbootDebug / FixBeginner · 4 min read

How to Handle Exceptions in Spring Boot: Simple Guide

In Spring Boot, handle exceptions by creating a class annotated with @ControllerAdvice and defining methods with @ExceptionHandler to catch specific exceptions. This approach centralizes error handling and returns meaningful responses to clients.
🔍

Why This Happens

When an exception occurs in a Spring Boot controller and is not caught, the server returns a generic error response, often a 500 Internal Server Error. This happens because the application does not have a defined way to handle unexpected errors gracefully.

java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @GetMapping("/error")
    public String error() {
        throw new RuntimeException("Something went wrong");
    }
}
Output
HTTP 500 Internal Server Error with default error page
🔧

The Fix

To fix this, create a class annotated with @ControllerAdvice and add methods annotated with @ExceptionHandler to catch exceptions and return custom responses. This way, you control what the client sees when errors happen.

java
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(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return new ResponseEntity<>("Custom error message: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Output
HTTP 400 Bad Request with body: "Custom error message: Something went wrong"
🛡️

Prevention

Always anticipate possible errors and handle them centrally using @ControllerAdvice. Define specific handlers for different exception types to provide clear feedback. Avoid catching exceptions only in controllers to keep code clean and maintainable.

Use meaningful HTTP status codes and messages. Consider logging exceptions for debugging. Use validation annotations to prevent invalid input that causes exceptions.

⚠️

Related Errors

Common related errors include:

  • 404 Not Found: Happens when a requested resource does not exist. Handle with @ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class).
  • MethodArgumentNotValidException: Occurs when validation on request data fails. Handle to return validation error details.
  • AccessDeniedException: Happens when user lacks permission. Handle to return 403 Forbidden with a message.

Key Takeaways

Use @ControllerAdvice with @ExceptionHandler to centralize exception handling in Spring Boot.
Return meaningful HTTP status codes and messages to clients for better error understanding.
Avoid handling exceptions only inside controllers to keep code clean and reusable.
Validate inputs early to prevent exceptions caused by bad data.
Log exceptions to help with debugging and monitoring.