2 ms·
My thoughts (as a Java / C# developer that occasionally dabbles in Ruby, Python, Go, JS and other languages): * Throw exceptions when things are broken *
by joshka 4y ago
My thoughts (as a Java / C# developer that occasionally dabbles in Ruby, Python, Go, JS and other languages):
* Throw exceptions when things are broken
* Catch exceptions when the calling code can do something other than propagate the error
* Log exceptions at the level where they are uncaught
* Log information about errors that are handled rather than the exception detail
* Never log and propagate the error. This often leads to double logging, especially when the error
is further propogated. This in turn causes confusion about whether there is one error or two, as
well as whether one error is a cause or is caused by the other error.
* Always provide enough information in your own exceptions about:
* what you were trying
* what went wrong
* what the caller can do to fix the issue (even if that's an indication that nothing can be done)
* Never discard information about an exception unless it will truly never serve any purpose
* Consider storing (but not writing) debug log messages that are only used when something does crash.
How we got to this point is usually the most important thing a developer needs to know. Google "Ring
Buffer Logging"
* Always think about how you would prevent the error from happening rather than letting it fail
* Log errors at system boundaries and report useful errors to the external system
* Never include confidential info in errors (passwords, keys, tokens)
* Ensure errors can be correlated in some way (request ID / correlation ID etc).
* Ensure that the contextual level of the exception matches the level that the caller expects.
E.g. an error throw by code that saves a customer record generally shouldn't ever be a FileNotFound
or a DivideByZero error even if this is what happened somewhere down the stack.
These are generalizations, and like many rules can be broken if it makes sense. Do so with good reason though.