Exception Handling in Spring Boot

 ๐Ÿงฐ Common Ways to Handle Exceptions in Spring Boot

✅ 1. Using @ExceptionHandler in a Controller

This handles exceptions locally for a specific controller.


java

Copy

Edit

@RestController

public class MyController {


    @GetMapping("/user/{id}")

    public User getUser(@PathVariable Long id) {

        return userService.findById(id).orElseThrow(() -> new UserNotFoundException(id));

    }


    @ExceptionHandler(UserNotFoundException.class)

    public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

    }

}

✅ 2. Using @ControllerAdvice for Global Handling

This is the recommended and reusable way to handle exceptions across the entire app.


java

Copy

Edit

@ControllerAdvice

public class GlobalExceptionHandler {


    @ExceptionHandler(UserNotFoundException.class)

    public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {

        ErrorResponse error = new ErrorResponse("USER_NOT_FOUND", ex.getMessage());

        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);

    }


    @ExceptionHandler(Exception.class)

    public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {

        ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "Something went wrong");

        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

    }

}

✅ Define your ErrorResponse DTO for consistent API responses.


✅ 3. Custom Exceptions

java

Copy

Edit

public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(Long id) {

        super("User not found with ID: " + id);

    }

}

✅ 4. Validation Exception Handling

When using @Valid or @Validated, Spring throws MethodArgumentNotValidException.


java

Copy

Edit

@ExceptionHandler(MethodArgumentNotValidException.class)

public ResponseEntity<ErrorResponse> handleValidationErrors(MethodArgumentNotValidException ex) {

    List<String> errors = ex.getBindingResult()

        .getFieldErrors()

        .stream()

        .map(error -> error.getField() + ": " + error.getDefaultMessage())

        .collect(Collectors.toList());


    ErrorResponse error = new ErrorResponse("VALIDATION_FAILED", String.join(", ", errors));

    return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);

}

✅ 5. ResponseStatusException

You can also throw exceptions with a response status inline:


java

Copy

Edit

@GetMapping("/user/{id}")

public User getUser(@PathVariable Long id) {

    return userRepository.findById(id)

        .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));

}

๐ŸŽฏ Best Practices

Practice Description

✅ Use @ControllerAdvice Centralized exception management

✅ Use custom exception classes Clear, reusable error semantics

✅ Return meaningful HTTP status codes E.g. 404, 400, 500

✅ Create a standard error response structure Consistency for API clients

✅ Log exceptions properly Helps with debugging


๐Ÿงช Example ErrorResponse Class

java

Copy

Edit

public class ErrorResponse {

    private String code;

    private String message;


    // constructors, getters, setters

}

Learn Full Stack JAVA Course in Hyderabad

Read More

Spring Boot Annotations You Must Know

Dependency Injection in Spring Framework

Creating REST APIs using Spring Boot

Spring Boot vs Spring MVC – Key Differences

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions 

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Waits in Playwright: Explicit, Implicit, and Auto