B
B
believe_me2021-09-13 16:36:06
Java
believe_me, 2021-09-13 16:36:06

What is the best way to handle a custom exception in Spring MVC?

It is necessary to avoid adding a duplicate entry in the controller.
Controller:
613f52f325702338563241.png
CategoryDao:
613f533cd3f64143225782.png

How ok is it to be tied to the logic of the thrown exception? like in the #isExistByName method?
If it's not ok to do this, then what approach is better to use? rewrite the method that will check if there is an entry in the database without calling the third-party #getByName method?

I re-read and reviewed many examples, but I don’t know what architectural solution to come to.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-09-13
@believe_me

Good evening.
1) First of all - instead of screenshots, add code snippets. If, for example, you have to make changes to your code, then what do you want to do? Do not reprint it from the screen.
2) It is better to transfer the check for duplicates and other logic to the service layer.
For example, a certain CategoryService, where the business logic is processed, and then the CategoryDao methods are called in the service layer
3)

How ok is it to be tied to the logic of the thrown exception?

Throw your custom exception in the service layer. For example, DuplicateRecordExistsException, RecordExistsException or something like that.
Next, catch this exception at the controller level or controllerAdvice. And then, based on the thrown exception, send a message with the http status to the client. For example,
the presence of a duplicate is an error on the client. Accordingly, the error code is 4xx (for example, 400). Error message - Entry exists.
Read this - https://spring.io/blog/2013/11/01/exception-handli...
Pay attention to
@ExceptionHandler
and also this chapter - Global Exception Handling Using @ControllerAdvice Classes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question