This document is the example project for the following blog post: Error Handling Best Practices in Spring Boot with Kotlin.
This project is a Kotlin-based application that showcases error handling in Spring Boot with Kotlin
The Example API provides endpoints for managing users. It allows you to:
Retrieve a user by their ID.
Create a new user, with validation to ensure the name is not blank and to prevent duplicate user names.
The API also includes comprehensive error handling to return appropriate HTTP status codes and error messages for various scenarios, such as resource not found, validation failures, and duplicate resources.
To build the project, you need to have Gradle installed. You can build the project using the following command:
./gradlew build
To run the tests, use the following command:
./gradlew test
Defines a data class User
with properties id
and name
.
Contains the UserService
class with methods to find a user by ID and create a new user. It throws an exception if a user with the name "Alice" already exists.
Defines a data class CreateUserRequest
with a single property name
, which must not be blank.
Handles specific business exceptions like ResourceNotFoundException
and DuplicateResourceException
, returning appropriate HTTP status codes and error messages.
Defines custom exceptions for resource not found, duplicate resource, and invalid operation scenarios.
Handles general exceptions and validation errors, returning appropriate HTTP status codes and error messages.
Defines a data class ApiError
to structure error responses with properties like status, message, errors, timestamp, and path.
Defines a REST controller with endpoints to get a user by ID and create a new user. It uses UserService
and handles exceptions for resource not found and duplicate resource scenarios.
Contains test cases for the error handling in the application, including scenarios for resource not found, validation failure, and duplicate resource conflict.
This project is licensed under the MIT License.