Avoiding exceptions vs handling exceptions in Java [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am implementing a DELETE rest endpoint in spring boot, I am not sure which approach is better between below 2 approaches:
First checking if the record with given Id exists in the database and then delete it safely.
Directly calling delete on spring data repository and catching EmptyResultDataAccessException thrown by spring data to return 404 response.
I like the first one as the code is more readable and does not involve controlling flow using exceptions. However, it involves an additional call to db and potential race condition.
Why would you prefer the first or the second approach?

If you annotate the service method with #Transactional there will be no race condition and it's fine to check for existence first (with a small performance overhead).
On the other hand I always like the simplicity of attempting the deletion and catching the exception, the assumption being that deleting a non-existent resource is exceptional.
Note also that in REST a DELETE on a non-existing resource should normally return a succesful HTTP status code 200 (OK) or 204 (NO_CONTENT).
#Transactional
public Response deleteAfterChecking(Thing thing) {
if (!repository.exists(thing)) {
repository.delete(thing);
}
return Response.NO_CONTENT;
}
public Response deleteHandlingException(Thing thing) {
try {
repository.delete(thing);
}
catch (NotFoundException e) {
// do nothing
}
return Response.NO_CONTENT;
}

The first option is better conventions-wise and will be more readable, but not performance-wise on big amounts of data as you will need two calls. Indeed, you should not need to catch an EmptyResultDataAccessException at any point.
You should nonetheless think about your code conception. How can the ID of a potentially non-persisted object be passed ? Is it necessary ? Without your code, I can't judge, but I believe you should consider this.

Related

alternative to try finally for logging in Java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Many methods in my code I am currently working on follows a certain pattern:
public void aMethod(...) throws CustomException {
Log("aMethod Started")
try {
//Many method calls that could throw a CustomException
} finally {
Log("aMethod Ended")
}
}
Changing anything about the CustomException is not an option.
Is there any better alternative that doesn't work with try finally?
I would say
finally {
Log("aMethod Ended")
}
is not good way to log ending of method.
If an exception occurred the method has not actually ended but interrupted and returned without completing.
So, the "Log("aMethod Ended")" shall be outside of finally. If end logger is missing in that log, you will anyway get from the exception stack trace.
If you want to just log weather the method was called and then left, then Spring AOP is what could be implemented for the whole product configuration, so you wont need to duplicate the logger everywhere.
On the other hand, if you personally feel this logger wont be of much use and just redundant information; then just turn off that rule in solar lint configuration.

Test an if condition with mockito [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code of the if statement:
if (reponse.getStatus() >= HttpServletResponse.SC_BAD_REQUEST) {
LOGGER.error("Erreur lors de l'enregistrement de la trace technique - {}", reponse.getStatusInfo().getReasonPhrase());
}
Basically testing always consists of two parts:
preparing some input, so that your production code under test takes a specific path
verifying that the expected "things" happened
First one is easy: you have to somehow make sure that the response object that your production code is dealing with has the required status. How you do that, very much depends on context.
For the second aspect, that is probably hard. You see, the only action taking place is a (probably static) call to that error() message. If that is the case, then your only way of testing this would be to use JMockit or PowerMock(ito), because those two frameworks allow you to verify static method calls.
So, the real answer is:
figure for yourself how you can gain control over that response object
buy into using one of these mocking frameworks (not recommended)
rework your code so that it becomes testable without adding that (imho really really bad) dependency towards PowerMock(ito).

Standard for Exception Handling [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am writing an API, which will return some response, of course. There is a chance of the exception.
There are two options of response in the case of any exception:
Return some error message in response and let your consumers know what is going on.
Rather than error message return default response and don't let
consumers know If something bad is going on.
I know both approaches has its own pros and cons.
I just want to know, which one is the better approach to adopt and why?
An API should never leave its users wondering why they are not getting the expected response.
Errors forwarded to the users should be of at least two kinds:
errors due to invalid parameters passed to the API calls. This is an user error. If your API exposes HTTP, a 400 error is expected.
(unexpected) errors that happened on the API server although the supplied parameters were correct. If your API exposes HTTP, a 500 error is expected.
For user (400) errors, the API should provide the maximum details on the error so that the user can correct its input.
For server (500) errors, this is up to you, but the more details, the easier support calls will be to answer. Since this is likely a bug, a stacktrace is a big help for a developer to fix the issue.
1. Return some error message in response and let your consumers know what is going on.
You should try to extend the Exception class and define your own Exception Codes and then throw this custom exception object instead of SQLException or DataAccessExceptions.
Later you can also provide a basic manual for troubleshooting the errors based on the custom codes you defined.
It is a bad idea to show the SQL Trace/Exception to the end user as it may reveal some important information about your application such as SQL Queries, DB Schema and Table Names etc.
2. Rather than error message return default response and don't let consumers know If something bad is going on.
This is not a recommended approach as it will leave the users in state of a mystery of what's going wrong with the API and what they can do to fix it.

Which type of exception should be generalized or created a base class for in a Java architecture [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As a team lead which type of exception should I create a base class for in my architecture - checked or unchecked ? My team would start development in a few weeks and I want the architecture to be conducive to them for usage. Any reasons around that would also help.
That depends on the situation.
You use checked exceptions (extend Exception) for things that can go wrong regardless of the input the caller of the method passes. For example, network connections; you can make an HTTP GET request by calling client.get("google.com"); and everything goes well, two minutes later you call once again client.get("google.com"); and then you get an exception because of a network error. As you can see, here you called the same method passing the exact same input "google.com", yet you can get an exception at anytime. Therefore, you must force the caller to catch the exception by making it "checked", so that they handle those cases in which a network error occurs.
You use unchecked exceptions (extend RuntimeException) when the error happens because of some sort of invalid input by the caller of the method. For example, you have the method Integer.parse(String);. The method cannot work properly if you pass a null string here, so you throw an exception if that happens. This case, you should not force the caller to catch it, because the caller is responsible of passing the right input.
Overall: let the them decide, start with a short discussion. Helps people getting to know each-other.
I'd avoid checked exceptions: since they need to be explicitly catched, the catch block could become part of the normal program flow. Increases complexity and thus chance of introducing bugs.
Also don't use custom exceptions when possible, use existing exceptions like IllegalArgumentException. Avoid NullPointerExceptions by never returning null. Furthermore try to use something like bean-validation. That can save a lot of errors in your code caused by invalid (combinations of) arguments. And last but not least, failing fast is better then making your own faulty retry logic.

Spring Roo: Trigger Action on Update – Best Practice [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have played a bit with Spring Roo, now I am asking myself what is the Roo suggested way or best practice way to trigger an action after an object update.
Let me explain it with an example:
Assume I want to implement a web based Bug Tracker (I don’t want to do this, it is only an example). A bug tracker, is about Issues. Each Issue has a state (New, Confirmed, Assigned, In Progress, Resolved.), a title and some other fields.
The user has a web form where it can enter and update all fields (state, title, …). When the state of an issue switches from ‘In Progress’ to ‘Resolved’, the system should send an email to all persons that are interested in the bug (How this list of interested persons is maintained, is out of scope for this problem).
The problem that I have is: How to trigger the email sending process when the state is changed (in a Roo application)? Because there are several problems:
How to determine if the issue state is changed?
We need to make sure, that the message send after the issue is complete updated (for example it would not work, to put the trigger in the setState() method of the Issue, because it is not guaranteed that the other values from the form (title…) are updated before the state is changed.
The mail must only be sended if the form was valid and the Issue is likely to be saved (I do not facing the problem that the transaction cannot be committed – this will be another problem)
Does anybody have a good, testable (unit tests) and maintainable solution? Maintainable means especially that the code to handle this should not be placed in the controller, because it will be used in several controllers and someday somebody will implement an new controller and he will likely forget to handle this email concern.
You can use the #PostUpdate annotation, a JPA life cycle callback listener.
class Issue{
#PostUpdate
protected void onPostUpdate(){
//This method wil run after the update
if(this.state == Resolved){
//...
}
}
Here is more information about the available callbacks.

Categories

Resources