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 -
Hi for your questions:
it depends in your business logic for example you have a service layer to update a user, you should find it by ID, if user not found you should throw an exception
if you are using spring-boot is a framework to provide for you ready libs and APIS to handle all you can check this link https://www.baeldung.com/exception-handling-for-rest-with-spring
Yes; because the controller is responsible for handling the Http exceptions, the service the business layer
I didn't understand this question
No it's not necessary, it's recommended to return the Http error code with custom message for the client to understand exception error cause
I recommend following jhiptser spring boot project structure, https://www.jhipster.tech/managing-server-errors/
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.