NOTE
Designing an Error System
An error system distinguishes critical and ordinary problems before deciding whether to stop or continue. These notes cover codes, context, propagation, and related 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. How ordinary errors are handled depends on the situation.
3. Error Construction
Include the following details when creating an error.
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
- Propagate the error to the caller.
- 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
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub