Software Design/Provide context information in exception and error logging messages
Checklist questions:
- The exception is created with a descriptive message with the relevant context information provided?
- Exception is not created with a non-constructive message such as "oops!", "wtf", "error", etc.?
- Logged message includes all relevant context information?
When throwing an exception, create it with a message that describes the nature of the exceptional situation (unless the programming language supports exception classes and the class of the thrown exception itself identifies the nature of the exceptional situation) and the reason for the exceptional situation, if known. Make sure that the exception's message includes the information that would allow debugging the error, for example:
- The name of the function where the exceptional situation occurred (unless the programming language and the runtime environment take care of collecting and presenting stack traces of thrown exceptions themselves).
- The data being processed, such as argument values for the function where the exception is thrown.
- The state of the object (in object-oriented languages, when the exception is thrown from a function belonging to the class of the object) or the subsystem from where the exception is thrown.
- The root cause of the exception, such as another exception. If the programming language supports a conventional way to provide this information, such as
Throwable.addSuppressed()
in Java, it should be used.
This practice equally applies to logging statements.
This practice corresponds to Item 75: "Include failure-capture information in detail messages" in Effective Java.[1]
Why
editDescriptive error messages and inclusion of relevant context information makes the error behavior traceable and thus reduces the time needed to investigate the problem.
Why not
editEmitting detailed context information may have security and privacy implications.[1] For example, if an exceptional situation occurred when processing some data for some user, logging the user's data may expose the private information about the user to operators of the system. For another example, some web server technologies and frameworks propagate the error information to the client. A detailed error message with a stack trace exposes some information about the website's internals to the client and may help to create an exploit to the website.
References
edit- ↑ 1.0 1.1 Effective Java (3 ed.). 2018. ISBN 978-0134685991. Item 75: "Include failure-capture information in detail messages"