Skip to content

KotlinCraft/rest-api-error-handling

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This document is the example project for the following blog post: Error Handling Best Practices in Spring Boot with Kotlin.

Error Handling Best Practices in Spring Boot with Kotlin

Overview

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.

Building the Project

To build the project, you need to have Gradle installed. You can build the project using the following command:

./gradlew build

Running the Tests

To run the tests, use the following command:

./gradlew test

File Overview

User.kt

Defines a data class User with properties id and name.

UserService.kt

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.

CreateUserRequest.kt

Defines a data class CreateUserRequest with a single property name, which must not be blank.

BusinessExceptionHandler.kt

Handles specific business exceptions like ResourceNotFoundException and DuplicateResourceException, returning appropriate HTTP status codes and error messages.

exceptions.kt

Defines custom exceptions for resource not found, duplicate resource, and invalid operation scenarios.

GlobalExceptionHandler.kt

Handles general exceptions and validation errors, returning appropriate HTTP status codes and error messages.

ApiError.kt

Defines a data class ApiError to structure error responses with properties like status, message, errors, timestamp, and path.

UserController.kt

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.

ErrorHandlingTest.kt

Contains test cases for the error handling in the application, including scenarios for resource not found, validation failure, and duplicate resource conflict.

License

This project is licensed under the MIT License.