Is there a best practice on using the followng two pieces of code regarding exceptions.
//code1 } catch (SomeException e) { logger.error("Noinstance available!", e.getMessage()); } //code2 } catch (SomeException e) { logger.error("Noinstance available!", e); } When should I use the getMessage method of an exception?
76 Answers
The first doesn't compile because the method error accept a String as first parameter and a Throwable as second parameter.
e.getMessage() is not a Throwable.
The code should be
} catch (SomeException e) { // No stack trace logger.error("Noinstance available! " + e.getMessage()); } Compared with
} catch (SomeException e) { // Prints message and stack trace logger.error("Noinstance available!", e); } The first prints only a message. The second prints also the whole stack trace.
It depends from the context if it is necessary to print the stack trace or not.
If you already know why an exception can be thrown it is not a good idea to print the whole stack trace.
If you don't know, it is better to print the whole strack trace to find easily the error.
3This prototype is useful, when you classify exception into Business level and Technical exception.
For Business level exception, you just use the message, by logging for analytics or may be to display on the screen a meaning information (something didnt work).
For Technical exception, its better to log the error with stacktrace, to find of out the issue and it is easy to debug and resolve.
With stacktrace:
logger.error("Could not do XYZ because of: " + ex, ex); Without stacktrace:
logger.error("Could not do XYZ because of: " + ex); It depends if you need stack trace of original exception (SomeException). If yes, then code2 is correct option here. Note that is more common way of handling these situations.
If you are not interested in what was the original exception, you can use code1 but this one is not correct. Because the code you sent takes message as argument. So the correct way is:
logger.error("Noinstance available! - reason:" + e.getMessage()); You can try this:-
logger.error(e.getMessage(), e); It Returns the detail message string of this throwable.
logger.error(e.getLocalizedMessage(),e); Creates a localized description of this throwable. Subclasses may override this method in order to produce a locale-specific message. For subclasses that do not override this method, the default implementation returns the same result as getMessage().
In your case e is nothing but the object of exception ...
getLocalizedMessage() u need to override and give your own message i.e the meaning for localized message.
Exception.printStackTrace() should not be used unless youre for example debugging.
For logging, it is definetly better to use Exception.getMessage(). Also please notice that many logging frameworks (for example Log4j) accepts exception it self as an argument on logging method (for example error()) and works it out by itself.