Skip to main content

Command Palette

Search for a command to run...

Exception Handling in Spring Boot REST APIs (Complete Guide)

Updated
3 min readView as Markdown
S
Backend developer interested in Java, Spring Boot, and building scalable APIs. I write tutorials and share practical backend development concepts for developers and students.

Introduction

While building REST APIs, errors and exceptions are unavoidable. Applications may receive invalid input, missing data, or unexpected server issues.

Handling these exceptions properly is important for building reliable backend systems.

In this article, we will learn how exception handling works in Spring Boot REST APIs and how to create clean error responses.


What is Exception Handling?

Exception handling is the process of managing runtime errors in an application without crashing the system.

Examples of common API errors:

  • Resource not found

  • Invalid request data

  • Database errors

  • Null pointer exceptions

Without proper exception handling, APIs may return confusing or insecure error messages.


Why Exception Handling is Important

Proper exception handling helps to:

  • Improve API reliability

  • Return meaningful error messages

  • Improve debugging

  • Prevent application crashes

  • Provide better user experience

Professional backend systems always implement centralized exception handling.


Common Exceptions in REST APIs

Some common exceptions include:

  • NullPointerException

  • RuntimeException

  • MethodArgumentNotValidException

  • ResourceNotFoundException


Example Without Exception Handling

Consider the following API:

@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
    return userService.getUser(id);
}

If the user does not exist, the application may throw an exception and return an unclear server error.


Creating a Custom Exception

We can create our own custom exception class.

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}

This exception can be used whenever a resource is not found.


Throwing the Exception

Example:

public User getUser(Long id) {

    return userRepository.findById(id)
            .orElseThrow(() ->
                    new ResourceNotFoundException("User not found"));
}

If the user is missing, the custom exception will be thrown.


Global Exception Handling

Spring Boot provides @ControllerAdvice for centralized exception handling.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleException(
            ResourceNotFoundException ex) {

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

How This Works

Flow:

Client Request
    ↓
Controller
    ↓
Service Layer
    ↓
Exception Thrown
    ↓
Global Exception Handler
    ↓
Custom Error Response

This allows APIs to return clean and structured error responses.


Example API Response

Response:

{
  "message": "User not found"
}

HTTP Status:

404 NOT FOUND

Benefits of Global Exception Handling

Advantages:

  • Centralized error management

  • Cleaner controller code

  • Reusable exception logic

  • Better API consistency


Best Practices

  • Use custom exceptions for business errors

  • Avoid exposing internal server details

  • Return proper HTTP status codes

  • Use meaningful error messages

  • Implement centralized exception handling


Common HTTP Status Codes

Status Code Meaning
200 Success
201 Resource Created
400 Bad Request
401 Unauthorized
404 Resource Not Found
500 Internal Server Error

Conclusion

Exception handling is a critical part of backend development. In Spring Boot REST APIs, proper exception handling improves reliability, maintainability, and user experience.

By using custom exceptions and global exception handlers, developers can create professional and scalable backend applications.


Thank you for reading!