go:errors:custom_errors
Table of Contents
Custom errors
What is it?
A custom error is your own error type (usually a struct) that implements `Error() string`. It may include extra fields (code, operation, resource ID, etc.).
What is it used for?
- Return structured error details.
- Enable typed checks with `errors.As`.
- Add machine-readable info (e.g., HTTP status mapping).
Example
package main import "fmt" type NotFoundError struct { Resource string ID string } func (e *NotFoundError) Error() string { return fmt.Sprintf("%s not found: %s", e.Resource, e.ID) }
Notes / best practice
- Prefer pointers for custom error types when they have fields.
- Provide helper constructors like `NewNotFound(resource, id)`.
Hard words (English)
- structured /ˈstrʌktʃərd/: có cấu trúc
- machine-readable /məˈʃiːn ˈriːdəbəl/: máy đọc được
- constructor /kənˈstrʌktər/: hàm tạo
go/errors/custom_errors.txt · Last modified: by phong2018
