Error Structure
errors/errors.go:23-26
Error type includes:
- Code: HTTP/gRPC status code
- Reason: Application-specific error reason
- Message: Human-readable error message
- Metadata: Additional error context
- Cause: Underlying error (for error chains)
Creating Errors
Basic Error
errors/errors.go:68-76
Formatted Error
errors/errors.go:78-81
With Metadata
errors/errors.go:51-55
With Cause
errors/errors.go:44-48
Predefined Errors
Kratos provides constructors for common HTTP status codes:Error Inspection
Get Error Code
errors/errors.go:90-95
Get Error Reason
errors/errors.go:98-104
Convert to Kratos Error
errors/errors.go:128-152
Error Matching
errors/errors.go:36-41
HTTP Integration
Errors are automatically converted to appropriate HTTP responses:Custom Error Encoder
gRPC Integration
Errors are automatically converted to gRPC status:errors/errors.go:58-65
GRPCStatus
Convert to native gRPC status:Error Chains
Wrapping Errors
Unwrapping Errors
Error Metadata
Attach additional context to errors:Best Practices
Use Meaningful Reasons
Use Meaningful Reasons
Use UPPER_SNAKE_CASE reasons that clearly identify the error type (e.g.,
USER_NOT_FOUND, INVALID_TOKEN).Include Context in Messages
Include Context in Messages
Provide helpful error messages that aid in debugging without exposing sensitive information.
Preserve Error Chains
Preserve Error Chains
Use
WithCause() to preserve underlying errors for debugging while returning clean errors to clients.Don't Expose Internal Errors
Don't Expose Internal Errors
Convert internal errors (like database errors) to appropriate public errors before returning to clients.
Use Metadata for Details
Use Metadata for Details
Add validation errors and field-specific information to metadata rather than cramming it into the message.
Be Consistent
Be Consistent
Define error reasons as constants and use them consistently across your application.
Error Constants Example
Related Components
HTTP Transport
HTTP error encoding
gRPC Transport
gRPC error handling
Middleware
Error recovery middleware
Logging
Error logging