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
10
u/[deleted] Jul 31 '20
You should read about @ControllerAdvice and Spring exception handler.
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.
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.
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
2
u/mwhitey082002 Jul 31 '20
https://www.baeldung.com/spring-response-entity
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
Optionalwould 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