I want to continue executing my scenarios even if some fail in between in the cucumber report it should show it as a failure but should not stop the execution.
I tried using soft assertion class and using this
SoftAssertion sa = new SoftAssertion();
if (response.getStatusCode() == 200) {
Sytem.out.println("pAASED")
} else {
sa.fail("this is the failure");
}
but suppose I have two scenarios and for the first one the response is not 200 it is going to else block and failing the scenario
java.lang.AssertionError: this is the failure
at org.junit.Assert.fail(Assert.java:88)
it is not even going for the second scenario. Can someone help how can I achieve the expected result(i.e it should continue the execution irrespective of one getting failed)
Here you have two different things.
Error Code As Response
Exception
As per definition of exception from Oracle website :
An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's instructions.
In this way exception is totally different from normal flow of execution. So if you want to proceed even in case of exception you need to use the concept of exception handling. As below:
try {
response = yourMethodCall();
} catch (Exception e) {
log.error(e)
}
In above sample code:
Replace yourMethodCall() with actual method call.
Catch proper minimum exception. (In your case it should be AssertionError)
Consider logging of your exception for better debugging, as in the code. For that create log object.
Related
I have a Docker container with a Java application that uses a DB to persist some data. My application has a class that extends another one that is not code of mine (specifically SinkTask, a class from Kafka that is used to transfer data from Kafka to another system). When the application starts it opens a connection to the database. Sometimes, the database closes the connection and tasks start to fail. The exceptions thrown by these failures are catched in one part of my code and I can think of different ways to handle them:
1. Simply executing the code from within the application that stops and starts the connection again
2. Restarting the Docker container, creating a new connection in the process
I think the best solution is number 1. However, I wanted to know how could I trigger the second situation. My guess is that I should throw a new Exception in the catch block capable of terminating the application (remember that the SinkTask part of the code is out of my control). Would this be a good solution? Which kind of Exception should I throw in this case?
This is the part of the code where I catch the exception
private void commitCollections() {
for (SinkCollection sc : collections.values()) {
try {
commitCollection(sc);
} catch (Exception e) {
LOG.error("Error flushing collection " + sc.getTableName(), e);
}
}
transactionRecordCount = 0;
try {
connection.commit();
} catch (SQLException e) {
LOG.error("Commit error", e);
}
}
Throwing an Exception and letting it propagate in order to terminate the application is a perfectly nice solution. IMO, using System.exit(exit_code) would be better because it clearly describes what that code is doing.
In addition, docker will display the exit_code in the status of the container (docker ps -a), thus helping differentiate between different error conditions. When an uncaught exception is thrown the exit code is always 1.
Hope that helps.
Quote from the description of the rule (SonarQube 4.5.5):
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ }
catch (Exception e) { LOGGER.info(e.getMessage()); }
By providing the exception class to the logger a stack trace is written to the logs.
The problem in our code base is this:
By following the Tell, don't ask principle, we use checked exceptions as part of the, what we consider, normal execution paths and we don't want them to result in unreasonably large log messages.
A few examples: Servers responding with error codes, database statement executions failing on optimistic locking (concurrent users)...
My suggestion: Split this case in two.
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ }
catch (Exception e) { LOGGER.info(e.getMessage()); }
and
// Compliant - exception is lost (only message is preserved) but there is business logic handling the situation
try {
/* ... */
} catch (Exception e) {
LOGGER.info(e.getMessage());
*/ exception handling */
}
The rule squid:S00108 (code blocks must not be empty) would not catch the problem since there is a logging statement.
Is this not reasonable? Have I missed something of importance?
Note: I've rewritten the question to clarify my use case
I understand the arguments for maintaining the stack trace and all that, but I think it's going to bloat your logs for a < ERROR level event. One solution is to log the message as a WARN and log the exception object as DEBUG or TRACE. That way a normal user log config would not be flooded with business as usual stack traces, but it would still be possible to get a stack trace if necessary.
If it's causing hundreds of what you consider to be FP's then you should think about turning the rule off, or excluding it from your project files.
But to answer your question:
The point of exception logging is to leave enough information for investigators to figure out the cause of a problem.
If your messages are detailed, e.g.
The x in the y method broke because the frabjous was not day enough
then perhaps they fulfill that purpose. But what about a message like
Something went wrong
?
Further, you know exactly what each exception message means, but someday you'll presumably move on to bigger and better things. Will the next guy who supports the system have the same depth of knowledge? He may be grateful for the stacktraces and line numbers that tell him where to start looking...
But finally, I have to ask: why are you getting and logging so many exceptions that you flood the logger?
(Adding another answer to address the question as rewritten:)
Why would you both handle the exception and log it? If it's handled, there's no reason to log.
try to pass whole object to method than just a e.getMessage()LOGGER.info("INFO "e.);
I made many research on this subject without found a real answer.
Try to imagine a program which execute a multi thread calling a Callable.
For that, we launch an ExecutorService with a specific timeout which invoke all process.
So we have a try...catch block with multiple exception :
CancellationException for a timeout
ExecutionException if an exception is raised in the thread
InterruptedException for an abrupt stop...
Is the philosophy to log an message only, or to log the message and the throwable (so the stacktrace) ?
To sum up, should we do this :
} catch (CancellationException ce) {
logger.error("Timeout. Process cancelled", ce);
}
or just log the message error ?
Is stacktrace considered to appear only for bugs ?
Thank you.
For coding you should stick with the following pattern:
} catch (CancellationException ce) {
logger.error("Timeout. Process cancelled", ce);
}
The reason is that the Throwable captures the complete context of an error. If you omit parts of that context from the logger you'll never be able to access it later on if you need it. Even the Throwable class included with Java has been modified over time to include things like chained and suppressed exceptions. So even if you only want the message from this throwable you still might want to see the full stack traces for suppressed exceptions and exceptions causes.
On the output side, I think you can make that case that for some exceptions the stack trace is not important. In some cases the target audience must not or does not want to see exception stack traces. For these cases should leverage the features of the framework to change the published output to please the target audience. If the needs change over time you can tweak logging configuration without having to fix the application code.
When should i use below log levels? If there is any example that would be great.
Trace Vs Debug
Warn Vs Error Vs Fatal
WARN VS ERROR Vs FATAL
Will I need to use FATAL in my application code in first place?
I have never seen FATAL logging in any code still now in projects that i worked on till now.
I have read that, in case of FATAL program will end. If this is the case, I wonder how my log statement will execute.
Moreover, I think FATAL can not be used in the case of memory allocation as JVM will throw out of memory exception and exit the program. Hence developer can not log anything. If this is correct then where exactly i will use FATAL?
For ERROR and Warning:
In catch block, if I do not have a alternate logic (for error condition) to perform then, I will go and log exception with Error level, the exception will be transformed into user specific and displayed in screen.
At the same time, the Warn will be used when we have alternate flow /path to the exception logic.
For Debug
This will be to validate what and where the exception been thrown. What means the data that casued the error. Hence this can be used just before and after the complex logic of the code.
Please let me know if my understanding is correct
example:
class myLogLevel{
void method1( int empId)
{
log.trace("method1 starting") ;
try{
log.info("befor getting data from DB");
log.debug("executing the value for emp id : " + empId );
//DBConnection and code here
} catch (Exception1 e1) {
log.warn("record not found. So assigning default value");
// Code logic to assign default value
}
catch (Exception1 e1) {
// Due to DB connection error. Connection nor established
log.error("DB connection not established");
}
log.trace("method1 ending") ;
}
}
In my past experiences, a somewhat common practice is
Always use DEBUG for your debugging purpose. I seldom see people use TRACE.
For stuff which is bad for the system but not necessarily cause problem (i.e. if it's an error depends on the calling context), use WARN; E.g. you could write a function which sometimes return NaN; but NaN might not be an error for the caller depends on your context.
For stuff that's surely an error somewhere in the system or in the caller input data; that definitely needs human involvement (i.e. someone needs to look at it from your production support team), uses ERROR. E.g. you want to write a person's record into database but found the primary key (firstname, lastname) is NULL.
For stuff that would cause the entire system to shut down or cause seriously impact on the system, use FATAL. That means people needs to look at it immediately. Examples include problems that cause startup failure; memory allocation failure; A messaging processing system failed to initialize the messaging layer; etc.
Hope the above helps.
Hi i´m development and app with Netbeans Platform and i can´t catch this exception:
org.hibernate.exception.ConstraintViolationException
I use the follow line:
try {
il.delete(lote);
}
catch (HibernateException he) {
NotifyDescriptor error = new NotifyDescriptor.Message(ERROR+he.getMessage(), NotifyDescriptor.ERROR_MESSAGE);
DialogDisplayer.getDefault().notify(error);
}
My interface may throw this exception, and the exception can be captured in the TopComponent. The problem is that I get twice, one is my notification and another from the platform.
How I can fix this?
In case of above code there is no possibility that you will receive exception twice. Because there is only one method call which returns exception.
What might possibility is you might be requesting it two times so that you are receiving exception multiple times.
What you can do is add a log check if method is being called multiple times on single click and fix that issue.