VIVO Documentation
Page History
...
This is not a good way to handle an exception:
No Formatcode |
---|
} catch(Exception e) { } |
An exception occurred, but we ignored it. Don’t do this. Please.
This isn't very good either (although, to be fair, it is better than a kick in the head):
No Formatcode |
---|
} catch(Exception e) { e.printStackTrace(); } |
...
In Vivo and Vitro, we use Apache Commons Logging. Create a logger in your Java code with a couple of imports and a static variable:
No Formatcode |
---|
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class MyClass { private static final Log log = LogFactory.getLog(MyClass.class); ... |
In the Vivo Harvester, we use Simple Logging Facade 4 Java. Create a logger in your Java code much like ACL:
No Formatcode |
---|
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyClass { private static Logger log = LoggerFactory.getLogger(MyClass.class); ... |
...
So, if this isn't good, how can we improve on it?
No Formatcode |
---|
} catch(Exception e) { } |
This is better. We’re still ignoring it, but we could stop ignoring it just by raising the logging level:
No Formatcode |
---|
} catch(Exception e) { log.debug(e, e); } |
This is better still. Here is a clue as to why we’re ignoring the exception.
No Formatcode |
---|
} catch(Exception e) { // This happens if the model data is bad - it's not important log.debug(e, e); } |
...
Not like this, for reasons mentioned earlier:
No Formatcode |
---|
} catch(Exception e) { e.printStackTrace(); } |
This is better:
No Formatcode |
---|
} catch(Exception e) { log.error(e, e); } |
If you have an idea of why a certain exception might be occurring, this would be the best:
No Formatcode |
---|
} catch(IllegalStateException e) { log.error("One of the flay-rods has gone out of skew.", e); } catch(Exception e) { log.error(e, e); } |
...
So, this probably doesn't do what you wanted:
No Formatcode |
---|
} catch(Exception e) { log.error(e); } |
It logs the class of the exception, and the message in the exception, but it doesn't write the stack trace. That's why this is better:
No Formatcode |
---|
} catch(Exception e) { log.error(e, e); } |
This way, the Exception class and it's message are written to the log twice, but that's a small price to pay – at least you get the stack trace in the log as well.
And this is best:
No Formatcode |
---|
} catch(ExpectedTypeAException e) { log.error("Some informative message explaining why TypeA might occur", e); } catch(ExpectedTypeBException e) { log.error("Some informative message explaining why TypeB might occur", e); } catch(Exception e) { log.error("Some informative message explaining that an unexpected error occurred", e); } |
...