I am working on a spring boot application , which makes http calls to multiple external services, aggregates and returns the response to the frontend.
Here's the current structure of my project:
RouteController -> Handler -> ServiceLayer
Note - This application will always send a Http 200 response, unless all service calls fail.
Spring exception handling https://www.baeldung.com/exception-handling-for-rest-with-spring is for class/controller level and conveys the Http response code to the client.
What I'm looking for here is exception handling inside the application.
I'm trying to add exception handling in this service, and there doesn't seem to be a clear concise rule.
This is a custom exception i have created for any dependency failure -
class DependencyException : RuntimeException {
constructor() : super()
constructor(message: String?) : super(message)
constructor(cause: Exception?) : super(cause)
constructor(message: String?, cause: Exception?) : super(message, cause)
}
Here's the code in service layer making a call to UserService -
fun getUsers(): List<User>? {
logger.info { "entered: getUsers " }
val response = userControllerApiClient.getUsers()
when (response.statusCode.is2xxSuccessful) {
true -> return response.body?.users
false -> throw DependencyException()
}
}
Have used org.springframework.http
library for http calls.
There are a few questions I couldn't find a clear answer of -
When should a service write its own exceptions? Whenever existing exceptions in standard library don't cover your use case, or when you want to add more details in an exception.
When to use kotlin/java standard lib existing exceptions? Same as above, don't try to reinvent the wheel. Like ,Use IllegalArgumentException instead of creating you own InvalidRequestException . Take a look here - https://programming.guide/java/list-of-java-exceptions.html
Here's a few resourced I think you should look at -
https://itnext.io/graceful-error-handling-in-rest-driven-web-applications-d4209b4937aa