Common error handling pitfalls
Factor handbook » The language » Exception handling

Prev:Post-mortem error inspection
Next:die ( -- )


When used correctly, exception handling can lead to more robust code with less duplication of error handling logic. However, there are some pitfalls to keep in mind.

Anti-pattern #1: Ignoring errors
The ignore-errors word should almost never be used. Ignoring errors does not make code more robust and in fact makes it much harder to debug if an intermittent error does show up when the code is run under previously unforseen circumstances. Never ignore unexpected errors; always report them to the user.

Anti-pattern #2: Catching errors too early
A less severe form of the previous anti-pattern is code that makes overly zealous use of recover. It is almost always a mistake to catch an error, log a message, and keep going. The only exception is network servers and other long-running processes that must remain running even if individual tasks fail. In these cases, place the recover as high up in the call stack as possible.

In most other cases, cleanup should be used instead to handle an error and rethrow it automatically.

Anti-pattern #3: Dropping and rethrowing
Do not use recover to handle an error by dropping it and throwing a new error. By losing the original error data and execution context, you signal to the user that something failed without leaving any indication of what actually went wrong. Either wrap the error in a new error containing additional information, or rethrow the original error. A more subtle form of this is using throw instead of rethrow. The throw word should only be used when throwing new errors, and never when rethrowing errors that have been caught.

Anti-pattern #4: Logging and rethrowing
If you are going to rethrow an error, do not log a message. If you do so, the user will see two log messages for the same error, which will clutter logs without adding any useful information.