NOTE
Designing an Error System
A historical note on error classification, error codes, context, propagation, logging, and caller-facing error handling.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is an Error?
An abnormal problem that occurs while a program is running.
2. Error Classification
Errors can be divided into two categories by severity: severe and ordinary. A severe error should terminate the program, for example when resource initialization fails during program startup. Ordinary errors depend on the situation.
3. Error Construction
Creating an error should include detailed information as follows.
3.1. Error Code
Error codes can be grouped by error source or handling strategy, for example:
- Success.
- Unknown error.
- Client or input error.
- Upstream dependency error.
- Infrastructure or middleware error.
- Data error.
Concrete numeric ranges are system-specific.
3.2. Parameters
3.3. Result
What the parameters are and what the result is.
3.4. Error Cause
4. Error Handling
- Continue propagating it outward.
- Catch and handle it:
- Add extra information.
- Log the error.
5. Errors and Callers
Some error information must not be exposed to callers and needs to be hidden.
6. Example
The following pseudocode expresses the core idea without depending on any specific language, framework, or business system:
function build_error(code, message, context, cause = null):
error = Error(code, message)
error.context = context
error.cause = cause
return error
function handle_error(context, error):
log_error(context, error)
public_error = sanitize_error(error)
return public_error.code, public_error.message
- Preserve the error code, message, context, and original cause when constructing an error.
- Wrap an existing lower-level error instead of discarding the original error chain.
- Keep internal diagnostic details in logs.
- Sanitize errors before returning them to callers, exposing only stable and necessary codes and messages.
7. References
Notes on Error Codes How Should Error Codes Be Planned and Designed in API Programs? Go Error-Handling Best Practices
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub