L
L
Lopus2021-10-07 15:55:46
Java
Lopus, 2021-10-07 15:55:46

How to properly design error handling in layers?

I make a GET /api/news/5 request and expect to get json with data for id=5.

I get id in the controller, through the service I transfer it to the repository.
The repository returns an Optional.
The service checks if newsEntityOptional.isEmpty() then writes logger.warn and throws a javassist.NotFoundException.
The controller is throwing this exception above.

The question is, on which layer is it more correct to throw an exception? Maybe it's worth returning Optional to the controller, or vice versa, throwing an exception right from the repository itself?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2021-10-07
@Maksclub

The repository can have find() methods - returns Optional
and can have get() - returns either the desired object or an exception that can fly further or is intercepted by the controller and thrown further
at the controller level to catch exceptions, even if there is a global ErrorHandler further

O
Orkhan, 2021-10-07
Hasanly @azerphoenix

Good afternoon.
I prefer to do it this way.
At the repository level (FooRepository) I get Optional<Foo>. Further, at the service level (FooServiceImpl), which duplicates the repository method, I already get Foo or, in case of its absence, I throw a custom exception FooNotFoundException. Then some global ControllerAdvice catches this exception and returns http status 404 with custom text Foo Not Found.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question