Overview
It’s possible to define custom error types by implementing theError() method on them. Custom error types allow you to attach additional structured data to errors and provide more context about what went wrong.
Creating Custom Error Types
A custom error type usually has the suffix “Error” and implements theerror interface:
Using Custom Errors
Once defined, you can return custom errors from your functions:Type Assertion with errors.AsType
errors.AsType is a more advanced version of errors.Is. It checks that a given error (or any error in its chain) matches a specific error type and converts to a value of that type:
errors.AsType returns two values: the converted error value and a boolean indicating whether the conversion succeeded.Complete Example
Output
When to Use Custom Errors
When you need structured error data
When you need structured error data
Use custom errors when you need to attach additional structured information to errors, such as error codes, timestamps, or contextual data that callers might need to access programmatically.
When callers need to handle errors differently
When callers need to handle errors differently
Custom errors are useful when different error types require different handling logic. Callers can use type assertions to determine the specific error type and respond accordingly.
When building libraries or packages
When building libraries or packages
Libraries and packages often define custom error types to give users a clear, structured way to handle different error conditions that the package might encounter.
Best Practices
Name with Error suffix
Convention: custom error types should end with “Error” (e.g.,
ValidationError, TimeoutError).Export when needed
Export custom error types (capitalize them) when callers need to perform type assertions.
Include context
Store relevant contextual information in struct fields for better debugging.
Use pointer receivers
Return pointers to custom errors (
*argError) rather than values for consistency.Comparison with Standard Errors
| Feature | Standard Errors | Custom Errors |
|---|---|---|
| Creation | errors.New("message") | &CustomError{...} |
| Type checking | errors.Is() | errors.AsType() |
| Structured data | No | Yes |
| Use case | Simple error messages | Complex error handling with context |