r/javahelp • • May 29 '19

Best way to manage service layer and error handling in Java Spring?

Hey guys, I have an implementation question about the service layer in a Java Spring application. We are using the repository design pattern.

In the past, I would have the service layer make calls to the repository, handle mapping the returned entities to DTOs, and then return the DTO or list of DTOs from the service layer and put them in the payload in the controller.

However, at my current job everybody wraps the response from service layers in a result class. This result class includes the possible data of a generic type, as well as some fields like "hasError", "errorMessages", and "statusCode".

My question is, is this best practice? Would it not make more sense to use something like @ControllerAdvice in Spring, and throw an exception with an associated status code?

I think they did this because they wanted the response to always be the same structure, whether or not there was an error. However, I think it might be better practice to just look at the status code that is returned, and make a decision based on that. "errorMessages" and the other fields could just be included in the exception class.

I am curious your guys thoughts on this. I have found many examples using springs error handling tools, but no examples yet that use this wrapper result pattern.

17 Upvotes

9 comments sorted by

1

u/largepongus May 30 '19

Thank you so much everybody for the answers. You have all answered my question and then some! From what I have read, this is an acceptable pattern to use, and is not an anti-pattern.

I still prefer the idea of using ControllerAdvice, as /u/ickysticky said, it seems to be safer when dealing with unchecked exceptions or things you might not be expecting like OOM errors. But for now, since it appear to be an acceptable pattern, I will continue to do it how everyone else here does!

3

u/GabiF May 29 '19

RemindMe! 3days “Spring responses & error handling”

1

u/RemindMeBot May 30 '19

I will be messaging you on 2019-06-02 00:04:22 UTC to remind you of this link.

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


FAQsCustomYour RemindersFeedbackCodeBrowser Extensions

0

u/GabiF May 29 '19

First time using this bot, hope it works

3

u/KeepItWeird_ May 30 '19

People do both. You are right in terms of you should be using HTTP semantics which of course includes returning the right response status codes for errors like 401, 403, 503, etc. but lots of people also want to provide additional messaging. Take a look at HAL protocol which is actually used by Spring Data REST. Also I think restapitutorial.com is a really good resource for basic API design guidance with minimal overhead / learning curve.

2

u/ickysticky May 30 '19

I prefer throwing exceptions and using @ControllerAdvice for two reasons.

First reason is that exceptions will happen, if you are calling out to any external code there is a very good chance that code will throw unchecked exceptions in at least some cases (most ORMs will do this, many spring components do this, etc). In addition you can always get VM level exceptions like OutOfMemory. What will happen in your current code to unhandled exceptions? If you are basically putting a top level generic exception handler in place to handle these, well that is just reinventing @ControllerAdvice on a per handler basis.

Second in my mind the service layer shouldn't know about the controller layer (ie it shouldn't know about HTTP, or status codes), the @ControllerAdvice gives you a good place to catch service layer exceptions and translate them into controller level error responses. For instance I often have something like a RequireUniqueException that gets turned into a response like you mentioned, where the error message is the exception message and the status code is 409 conflict, or a RequireExistException with a 404.

I think it is good to have a wrapper to all responses that give API clients a structured way to access error messages or the success value, but I think that using @ControllerAdvice to do that is the best way.

1

u/snot3353 COMPUTERS!!! May 30 '19

Depends how much you want to abstract things I guess. If you have anything at all related to a HTTP status code and are serializing error messages directly out of objects coming out of the repository/service layer then you start having the potential for leakage between layers. It's not too big of a deal until you start putting detailed stack traces and lower level error information into the actual API responses and start giving someone with malicious intent a little too much information.

I do usually use exception handlers in the controller or a @ControllerAdvice class like you suggested above.

1

u/AsteriskTheServer May 30 '19

They are the same solutions to the same problem in the same manner that there are different ways to log. One logging solution is not inherently a best practice, that being said, one way tends to emerge as a de facto standard, but that isn't a best practice persay just something people really like and agree with at the time. What really matters is whether the solution is consistently applied within the project. If so then the project code is easier to reason about because you don't think okay in this name space we use this error handling solution and in this name space we use this error handling solution. There is one way to handle responses so its easier understand the entire program, less error associated because everyone does it and so forth.

Personally I do what your job site currently does. Why? Mainly personal opinions, but ultimately inconsequential in the face of consistency.

1

u/nutrecht Lead Software Engineer / EU / 20+ YXP May 30 '19

I wrote a blog post on how to do that a while ago. ControllerAdvice is IMHO definitely the best way for actual exception flows because even if something 'bad' happens that you did not take into account you will still have a proper error response.

It also does not pollute all your layers with if-this-then-that-or-else-error code. And the way you guys are doing it is just more work too. More code = more potential for bugs.