How to get the stackTrace from an exception without printStackTrace? - java

Is it possible to get the whole trace from an exception without using printStackTrace()?.
One of the reasons it's because I use CheckStyle and I'm getting an ugly message. It's not enough just to call toString(). I want to get the complete message, because I needed to send me by email.
Currently, I'm doing
StringWriter e = new StringWriter();
exception.printStackTrace(new PrintWriter(e));
--Avoid tracing with printStackTrace(), use log4j instead.
Otherwise, I could disable CheckStyle there.

If you want to get error details try Apache Commons Lang api
There is a class ExceptionUtils . You can use getFullStackTrace

Have you tried?:
Throwable thr = e.getStackTrace();
StackTraceElement[] lines = thr.getStackTrace();
And working from there. Also, take a look at the javadocs Oli linked above

You can get the stack trace from the current thread,
check this :
Thread.currentThread().getStackTrace()

Try this, you will be able to print stack trace with no check style error.
import org.apache.commons.lang.exception.ExceptionUtils;
String errorMessage = ExceptionUtils.getFullStackTrace(exception);
logger.debug(errorMessage);

Related

Can log4j's error method print stack trace without string argument?

In regards to Log4j v2, I'd like to call log.error(exceptionTypeObj) and have the stack trace printed to my logfile instead of exceptionTypeObj.toString(). Is that possible?
I'd rather write code like log.error(e) and be done with it.
It's error prone and redundant for me to keep writing something like log.error("error", exceptionTypeObj).
The String parameter is redundant because you are not using it for the correct purpose. An Exception will tell you what error occurred but it won't tell you what you were trying to do when it happened. That is why you should always provide the string. Provide a String that says something like "Error occurred while attempting to update the user profile for user {}", and then provide the user name or id.
Without the String parameter you are forcing your support staff to call engineering to find out what the exception means and what they should do about it.

How to convert inputrstream or string to Exception?

I tried to execute jar from Java code with:
Runtime.getRuntime.exec("java -jar a.jar")
I could get InputStream with error from Process.getErrorStream().
Can I take this stream and if it has an Exception transform it to Exception and throw in my upper application?
Has Java some mechanism to convert string to Exception?
EDIT: Or maybe java has some mechanism like System.exit(int code) but with Exception? So in parent app I can do something like process.waitFor() but take an exception instead int code?
Process.getErrorStream() returns an IntputStream connected to the error output of the subprocess.
So, it is not exception in Java terms. It's an output information which must be considered as an error detected by the process during its execution.
Java don't convert automatically InputStream or String to Exception.
So, you could read this stream in a String and throw a custom exception with as message the string.
If you want that the caller may be able to handle this exception in a clean way, don't use a RuntimeException but a checked exception :
public class ProcessExecutionException extends Exception{
public ProcessExecutionException(String errorOutputMsg){
super(errorOutputMsg);
}
}
Edit for answering your comment :
Yeah, but how to check is inputstream line is a part of stacktrace of
child exception
it's not a stracktrace but error messages as explained.
and how much line from IS i should add to ProcessExecutionException?`
You have to read all the errorStream until it returns null if you want to capture all error output.
In my case my jar is a Spring Application and it write to error stream
nor only Exception that i really need to catch, also some information
like "Error, you have no sl4j xml file, etc - like example". And i
need only really important exception
How the classes producing errors in output may guess if it is important for you or not ?
You must decide yourself which error message pattern should be considered as an important error or not.
Personally, if when my process is run, I have a not well configured logger, I will kill it and correct this problem before starting it again.
If you have input in the ErroStream, you can also inspect the value of the Process.exitCode() (0: normal termination, else problem).
If it is different from 0, you can suspect that it not only a little problem.
Here, some tracks to try.
Can i return something to exit like in System.exit()
In the child process, you can try to intercept all exceptions not handled which may be triggered . You can do it whatever the way (aspect, global try/catch, filter...) .
In this way, if you intercept an exception not handled and that you consider that the application must be terminated, you can do a System.exit with the expected code by the parent process.
In this way, in the parent, if Process.exitCode() matchs with expected code for important exception, you can handle it as you wish.

Java Logging exceptions, use getMessage or toString : log.warn(ex.getMessage()) or log.warn(ex) working with open source

My question is: it better to log with getMessage or with toString or both? taking in to account errors thrown by open source. Saw the questions in the comments but did not get an answer to this. Maybe I missed something ? Do not mind the small performance hit of logging one of them, but do not want to log both unless there is a good reason.
Meaning log(ex) or log(ex.getMessage), Not talking about stack trace.
Saw 1 , 2 and 3
Logging exceptions : which is better:
log.warn(ex.getMessage(), ex) or log.warn(ex, ex);
I noticed sometimes getMessage returns empty or null, so in general practice is there any reason not to use :
log.warn(ex, ex);
As it seems to print the class name and the message (if set) ? I guess one reason could be if a sub class has over ridden to string not to print the message, but in reality do any of the hibernate, apache or spring libs do that?
How about
log.warn("some descriptive message, maybe with context {}",
someId, ex);
The exception details will already be printed as part of the stacktrace, so you don't need to include them in the message usually.
In case you want to suppress the stacktrace and only print the exception message, usually, ex.toString() works better than ex.getMessage(), because it also includes the exception class name, which the message does not. In fact, often the message is empty (for example with NullPointerExceptions).

Can I get a 'better' verbose output in Netbeans 7.3?

I'm trying to find an output mode that will show me the execution and order of every method called in the running program. Verbose and debugger output detail don't seem to give me that. Is there any way to get a detailed output like the one I've described here? Thanks!
You can do something like this using the following ways:
One: Put either of these codes in every method in your program:
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
System.out.println(new Object(){}.getClass().getEnclosingMethod().getName());
Two: Use the dumpStack() method:
Thread.currentThread().dumpStack();
Three: Use the printStackTrace of Throwable
new Throwable().printStackTrace();
Four: This is a variation of the first solution
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for(StackTraceElement st : stackTrace){
System.err.println(st);
}

Using e.printStackTrace() in Java

This is probably a newbie question, but hope you can help me. :) I have something like this:
try
{
//try to do something there
}
catch (IOException e)
{
//handle the exception
e.printStackTrace();
}
I am using NetBeans IDE and for some reason the printStackTrace is underlined in a squiggly line. When I press Alt+Enter, it says Throwable.printStackTrace() should be removed. What does this mean? Could anyone give more insight as what this may mean? Or can I ignore this?
Thanks!
Try:
e.printStackTrace(System.out);
It is just a recommendation. In eclipse it is fine - I believe it is just the IDE telling you that there are more conventional methods of doing it, like some of the other answers.
I find that it is useful for debugging, and that you should tell users when a fatal error is going to occur, to use a debug mode (like a console switch -d) to collect these logs.
It's probably because printStackTrace() doesn't really handle the error as much as it just dumps the stack in the console. It acts as a placeholder until you replace it with proper error handling (if it is needed at all) and replace the output with a logger of some sort.
e.printStackTrace();
Is not good practice because it prints in the default ErrorStream, which most of the times is the console!
NetBeans should be warning you about that. The good practice about it, is logging the message. Follow same reference:
http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html
EDIT
See first comment bellow to more info.
Just printing a stack trace is not enough. Printing the exception's stack trace in itself doesn't mean that it is completely bad practice, but printing only the stack trace when an exception occurs is an issue.
Always log exceptions(using a good logging framework), but do not expose them to the end-user. And keep ensure that showing stack traces only in development mode.
I myself use(most of the time) logger.log(Level.SEVERE, <exception>.getMessage(), <exception>);.
when netbeans suggest you to handle the exception 'Surround Statement with try-catch', if you click on this, it will generate):
try {
//something need to be handle(exception that throw)
} catch (SQLException ex) {
Logger.getLogger(ClassName.class.getName()).log(Level.SEVERE, null, ex);
}
Which is better than ex.printStackTrace();.
These may help:
Best Practices for Exception Handling
Javarevisited- logging's.
What are the latest options in Java logging frameworks?
Benchmarking Java logging frameworks.

Categories

Resources