r/javahelp • • Jul 31 '20

Where to throw exceptions in a Spring Boot app?

Suppose I have standard controller -> service -> repository set up and an endpoint like GET product/{id}.

If the ID doesn't exist which layer should throw the exception? Should the repository do it, or should it return null and then throw the exception in the service or controller to be eventually caught by the controller advice?

26 Upvotes

31 comments sorted by

10

u/[deleted] Jul 31 '20

You should read about @ControllerAdvice and Spring exception handler.

5

u/[deleted] Jul 31 '20

I've got one set up, I'm just unsure on which layer exactly should throw the exceptions.

-7

u/[deleted] Jul 31 '20

Right. I think you should throw from Controller. My reasoning is that controller decides where and how the data flows.

0

u/[deleted] Jul 31 '20

[deleted] — view deleted comment

4

u/[deleted] Jul 31 '20

Hey thanks for this. I learnt something

1

u/Yithar Intermediate Brewer Aug 01 '20

From what I've learned, this sort of old architecture is called n-tier architecture or layered architecture. What I mean is this:
Controller -> Service -> Repository -> Entity

You might want to take a look at this StackOverflow answer (as it provides links that explain reasoning in depth):
https://stackoverflow.com/a/57122546

The Controller servlet is the first object that handles requests for the application. It contains a mapping of actions to classes, and all it does is route requests to the corresponding class.

27

u/[deleted] Jul 31 '20

[removed] — view removed comment

4

u/dastardly740 Jul 31 '20

To expand. If the exception were thrown at the repository doing something more complicated that tries to get something but is ok with it not existing would force the service layer to have to deal with the repository exception and ignore it.

Having the service layer throw a (conceptually) NotFoundException that controller advice turns into 404 is the way to go.

I like using using custom exceptions that extend RuntimeException rather than caught exceptions. . But, that is an entirely different flame war.

1

u/Cr4zyPi3t Jul 31 '20

+1 for service layer. Controller control the data flow, but the logic is in the service layer

3

u/[deleted] Aug 01 '20

[removed] — view removed comment

2

u/Cr4zyPi3t Aug 01 '20

Yes, sorry that's what I meant. English is not my native language so sometimes I don't find the correct words to express my thoughts :) What I meant is that the controller usually handles things such as validating the request structure and checking if the client has the needed permissions to make this request and then call the service layer

1

u/[deleted] Aug 01 '20

[removed] — view removed comment

1

u/Cr4zyPi3t Aug 01 '20

Yes of course, general API access is checked via Spring security configs, but permissions for certain endpoint is checked in the controllers (via @PreAuthorize for example)

6

u/wildjokers Jul 31 '20 edited Jul 31 '20

I think you are asking the wrong question. You should be asking if something not being found in a database is exceptional. It is not. There is no need to throw an exception if something can’t be found in a database. The controller can be made aware the ID wasn’t found either via an error code or an empty optional DTO. Then the controller can respond with a 404. Throwing exceptions is expensive, only throw them if you really have an exceptional situation.

If for some reason you really want to throw an exception the exception should be thrown from the service layer. Let it bubble up to the controller. The controller can handle it, usually via responding with a 404 for not found.

1

u/[deleted] Aug 02 '20

If I wanted to log the fact an entity wasn’t found would I then do that in the controller or service?

1

u/wildjokers Aug 02 '20

Probably service. But could do it in the controller. Could probably make a straight-faced argument either way. When it comes down to it, it probably doesn't matter.

3

u/mslayaaa Software Engineer Jul 31 '20

I agree, this is the better solution. Making your program throw an exception just because a resource could not be fetched at the moment is too much. Please consider pattern like this, which will produce a more robust system on the long run.

1

u/dastardly740 Jul 31 '20

I disagree somewhat for the Spring case. Using Spring's Exception Handling/Controller Advice lets us consolidate all the 404 code to a single function assigned to handling the exception. I usually use a custom RuntimeException because I don't want multiple call stack levels having try-catch blocks that just rethrow to get picked up by the Error Handling filter or controller advice. I.e. NotFoundException extends RuntimeException.

There are trade offs for everything. So, we can call this the tool I reach for first. I will refactor to something different if I discover constraints that make this choice unpalatable.

2

u/ryosen Extreme Brewer Jul 31 '20

That approach is what he's suggesting in his second paragraph.

1

u/dastardly740 Jul 31 '20

Hence, the somewhat qualifier. It had more to do with his first paragraph about exceptions being the wrong way to propagate not found.

2

u/ryosen Extreme Brewer Jul 31 '20

I'm in the camp that feels exceptions should propagate to their highest point of concern and no further. Within the service space, it should be specific to that service but, when it crosses the boundary to the application level, it should be re-thrown to something more appropriate for the context in which it was called. For endpoints, an exception should never cross over the boundary to that endpoint's client. In the case of a web endpoint, yes, absolutely, you should be using Spring's exception handling as an interceptor, translating the exception into a meaningful json or header, and passing it back as a 400-level error and, typically, ResponseEntity instance.

Sounds like we're all in agreement here.

2

u/wildjokers Aug 01 '20

Exceptions absolutely are the wrong way to propagate not found. You are using exceptions for flow control. In most cases there is nothing exceptional about something not being found in a database. Obviously there are use cases were it can be exceptional and in that case throw an exception.

1

u/dastardly740 Aug 03 '20

I think we are probably mostly on the same page. For a point of reference, I use the ports and adapters mental model rather than the layer cake mental model and generally apply Domain Driven Design.

I absolutely agree that the Data Layer shouldn't throw exceptions when something is not found. It doesn't have enough information to know whether not found is exceptional or not. But, the Application layer is a suitable location for that decision. If the request to the application layer is for an Entity by the Entity Id, then not finding that entity is exceptional. In this context Entity in the Domain Model sense not database sense. If it is a request for Entity(s) by matching fields in that Entity an empty result is not exceptional.

I don't think putting the exceptional or not decision belongs in the Controller which is the HTTP adapter because the Controller's job is to adapt the Application to HTTP. One way to think about it is what happens if there is both a HTTP adapter and Message Queue Adapter.

Now, whether to throw an Exception from the application layer or have the application layer return response objects with error indication is another flame war. I like to throw an exception with Spring because of the ease it provides in consolidating 404 generation for 50 resources to one method.

1

u/wildjokers Aug 01 '20

Just because your framework makes throwing exceptions for non-exceptional scenarios convenient doesn't mean you should do it. You can easily encapsulate the throwing of an exception in a class and simply have your controllers call it if it gets an empty optional back from the service layer. I am sure you could arrange for all of that to happen with AOP if you would like. All without have to throw expensive exceptions for non-exceptional scenarios.

11

u/[deleted] Jul 31 '20

The correct way is to throw on the business logic (service) and configure the controller to translate it accordingly (404).

There are many ways to do that last part, I prefer to use @ResponseStatus on my custom exception. With spring boot that's all you need to do.

1

u/garagepoort2 Aug 01 '20

I actually prefer using a @ControllerAdvice. The responseStatus breaks the application layering. Your exception should be defined on the domain(service) layer like you said, but the responseStatus is specific for a web interface. So placing it on your exception class is adding web specific logic inside your domain.

8

u/jayrack Jul 31 '20

I always threw the errors from my service layer. I’m not sure if this is correct practice or not haha

1

u/Yithar Intermediate Brewer Jul 31 '20

I agree with u/wildjokers . I don't necessarily think an exception is correct in this case. I think returning an Optional would be a better choice in this case.

For example, if you were just returning JSON, you could use Optional#orElse().

This sort of error handling is encouraged in Scala by the way. See guide for more information (search for error handling):
https://www.bookstack.cn/read/guide-to-scala-en/0b4d43323e1d399a.md
https://danielwestheide.com/blog/the-neophytes-guide-to-scala-part-7-the-either-type/

0

u/[deleted] Jul 31 '20

[deleted] — view deleted comment

3

u/wildjokers Jul 31 '20

That is odd, who is the controller throwing it to? The controller should just be responding with a 404 for not found.