VIVO Documentation
Page History
This is a specialized sub-topic of The VIVO log file.
Not the Right Way
This is not a good way to handle an exception:
No Format |
---|
} 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 Format |
---|
} 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 Format |
---|
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 Format |
---|
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 Format |
---|
} catch(Exception e) {
}
|
This is better. We’re still ignoring it, but we could stop ignoring it just by raising the logging level:
No Format |
---|
} catch(Exception e) {
log.debug(e, e);
}
|
This is better still. Here is a clue as to why we’re ignoring the exception.
No Format |
---|
} catch(Exception e) {
// This happens if the model data is bad - it's not important
log.debug(e, e);
}
|
What if we do want to write the exception to the log? What's the right way to do it?
Not like this, for reasons mentioned earlier:
No Format |
---|
} catch(Exception e) {
e.printStackTrace();
}
|
This is better:
No Format |
---|
} 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 Format |
---|
} 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 Format |
---|
} 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 Format |
---|
} catch(Exception e) {
log.error(e, e);
}
|
...
And this is best:
No Format |
---|
} 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);
}
|
...