Answer the question
In order to leave comments, you need to log in
Is it worth throwing custom errors if the etity is not found in the API?
I think it's worth throwing your own exceptions if something is not found. On the one hand, this is logical and there will be no errors from Spring data JPA like EntityNotFoundException and much less understandable errors. But on the other hand, if everything is configured correctly from the front, then such situations should not happen. Also, Java will concatenate the strings that I pass to the error, even if there was no error.
I'm just learning and don't understand, here is an example of two code options.
First, I'm only concerned about string concatenation.
public VoteDTO getByid(int voteId) {
Vote vote = voteRepository.getById(voteId);
Optional<Vote> voteOptional = voteRepository.findById(voteId);
if(voteOptional.isEmpty()) {
throw new ApiException("Vote with id " + id +
"is not in DB");
}
return toVoteDto(voteOptional.get());
}
public VoteDTO getByid(int voteId) {
Vote vote = voteRepository.getById(voteId);
return toVoteDto(vote);
}
Answer the question
In order to leave comments, you need to log in
Good afternoon!
It probably depends on how you agree with the team.
You can throw custom actions, and then catch them in the Controller or ControllerAdvice and send the appropriate message to the client with an error code.
It is also possible to wrap an entity in an Optional and throw an exception orElseThrow()
or return another object ( orElse()
) or a new object, etc.
Optional<Vote> voteOptional = voteRepository.findById(voteId);
if(voteOptional.isEmpty()) {
throw new ApiException("Vote with id " + id +
"is not in DB");
}
Vote vote = voteRepository.findById(voteId).orElseThrow(VoteNotFoundException::new);
But on the other hand, if everything is configured correctly from the front, then such situations should not happen.
It makes sense to throw your own exception class if you have a handler described for this class, which will generate a business-correct http response, for example.
Here it is described how to do it
https://spring.io/blog/2013/11/01/exception-handli...
And the strings do not have to be concatenated, you can use StringBuilder or String.format() for example.
Is it worth throwing custom errors
I'm only concerned about string concatenation
throw new ApiException(String.format("Vote with id %d is not in DB", voteId));
public ApiException(String format, Object... parameters) {
...
}
throw new ApiException("Vote with id %d is not in DB", voteId);
I'm only concerned about string concatenation.
throws an exception in the business logic
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question