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
- RouteController routes to different handlers
- Handler makes call to multiple services, performs aggregates and returns response.
- Different ServiceLayers for each service call.
- Handler can return partial responses, if one service call fails it'll return the response of other calls.
- I have not added class/controller level exception handler as partial response can also be returned.
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?
- When to use kotlin/java standard lib existing exceptions?
- Should you propagate spring http exceptions to handler/controller layer ?
- Is the scope of dependency exception above too large?
- Should 4xx,5xx error codes be converted to different custom exception for internal handling? (And also different handling of different codes in each series? )
- What's the best way you'd recommend for handling exceptions in this project?