Documentation
¶
Overview ¶
Package ecode defines standardized error codes for API responses and provides utilities for error code management and localization.
This package provides:
- Predefined error codes for common scenarios
- Human-readable error messages
- Multi-language support (i18n)
- Error code to HTTP status mapping
- Custom error code registration
Error Code Convention ¶
Error codes follow a standardized numbering scheme:
- 0: Success (OK)
- -1 to -99: Application-level errors
- -100 to -199: Authentication/authorization errors
- -200 to -299: Request validation errors
- -300 to -399: Resource errors
- -400 to -499: Business logic errors
- -500+: Server errors
Common Error Codes ¶
Authentication errors:
ecode.NoLogin // -101: Not logged in ecode.UserDisabled // -102: Account suspended ecode.CaptchaErr // -105: Captcha verification failed ecode.UserInactive // -106: Account not activated
Request errors:
ecode.RequestErr // -400: Invalid request ecode.ParamErr // -401: Invalid parameters ecode.SignCheckErr // -3: Signature verification failed
Resource errors:
ecode.NotFound // -404: Resource not found ecode.Conflict // -409: Resource conflict ecode.AccessDenied // -403: Access denied
Server errors:
ecode.ServerErr // -500: Internal server error ecode.ServiceUnavailable // -503: Service unavailable ecode.Deadline // -504: Deadline exceeded
Getting Error Messages ¶
Retrieve human-readable error messages:
message := ecode.Text(ecode.NoLogin) // Returns: "Account not logged in" message := ecode.Text(ecode.ParamErr) // Returns: "Invalid parameters"
Custom Error Codes ¶
Register custom error codes for your application:
const (
InsufficientBalance = -1001
OrderExpired = -1002
)
ecode.Register(InsufficientBalance, "Insufficient account balance")
ecode.Register(OrderExpired, "Order has expired")
HTTP Status Mapping ¶
Error codes can be mapped to appropriate HTTP status codes:
httpStatus := ecode.ToHTTPStatus(ecode.NotFound) // Returns: 404 httpStatus := ecode.ToHTTPStatus(ecode.NoLogin) // Returns: 401 httpStatus := ecode.ToHTTPStatus(ecode.ServerErr) // Returns: 500
Usage with Response Package ¶
Error codes integrate seamlessly with the resp package:
import (
"github.com/ncobase/ncore/ecode"
"github.com/ncobase/ncore/net/resp"
)
resp.Fail(w, &resp.Exception{
Status: http.StatusUnauthorized,
Code: ecode.NoLogin,
Message: ecode.Text(ecode.NoLogin),
})
Localization ¶
Support for multiple languages:
// Set language for error messages
ecode.SetLanguage("zh-CN")
message := ecode.Text(ecode.NoLogin)
// Returns: "账号未登录" (Chinese)
ecode.SetLanguage("en-US")
message = ecode.Text(ecode.NoLogin)
// Returns: "Account not logged in" (English)
Best Practices ¶
- Use predefined codes when possible
- Keep custom codes in application-specific ranges (-1000+)
- Provide clear, actionable error messages
- Map codes to appropriate HTTP statuses
- Document custom error codes
- Use consistent error code patterns
- Return codes in API responses
- Log error codes for debugging
Index ¶
- Variables
- func AlreadyExist(k ...string) string
- func AssertionFailed(k ...any) string
- func Expired(k ...string) string
- func Failed(k ...string) string
- func FieldIsBlank(k ...string) string
- func FieldIsEmpty(k ...string) string
- func FieldIsInvalid(k ...string) string
- func FieldIsNil(k ...string) string
- func FieldIsRequired(k ...string) string
- func NotExist(k ...string) string
- func NotSingular(k ...string) string
- func Success(k ...string) string
- func Text(code int) string
- func TypeMismatch(k ...string) string
Constants ¶
This section is empty.
Variables ¶
var ( OK = 0 // Success AppKeyInvalid = -1 // Application does not exist or has been banned AccessKeyErr = -2 // Access Key error SignCheckErr = -3 // API signature check error MethodNoPermission = -4 // Caller has no permission for this method NoLogin = -101 // Account not logged in UserDisabled = -102 // Account suspended LackOfScores = -103 // Lack of scores LackOfCoins = -104 // Lack of coins CaptchaErr = -105 // Captcha error UserInactive = -106 // Account inactive UserNoMember = -107 // Account not a formal member or in adaptation period AppDenied = -108 // Application does not exist or has been banned MobileNoVerfiy = -110 // Mobile phone not bound CsrfNotMatchErr = -111 // CSRF check failed ServiceUpdate = -112 // System is upgrading UserIDCheckInvalid = -113 // Account not yet verified UserIDCheckInvalidPhone = -114 // Please bind your mobile phone first UserIDCheckInvalidCard = -115 // Please complete real-name authentication first NotModified = -304 // Not modified TemporaryRedirect = -307 // Temporary redirect RequestErr = -400 // Request error AccessDenied = -403 // Access denied NothingFound = -404 // Nothing found MethodNotAllowed = -405 // Method not allowed Conflict = -409 // Conflict Gone = -410 // Gone ServerErr = -500 // Server error Deadline = -504 // Service call timeout LimitExceed = -509 // Exceed limit FileNotExists = -616 // File does not exist FileTooLarge = -617 // File too large FailedTooManyTimes = -625 // Too many login failures UserNotExist = -626 // User does not exist PasswordTooLeak = -628 // Password too weak UsernameOrPasswordErr = -629 // Incorrect username or password TargetNumberLimit = -632 // Operation target number limit TargetBlocked = -643 // Blocked UserLevelLow = -650 // User level too low UserDuplicate = -652 // Duplicate user AccessTokenExpires = -658 // Token expired PasswordHashExpires = -662 // Password timestamp expired AreaLimit = -688 // Geographic area limit CopyrightLimit = -689 // Copyright limit FailToAddMoral = -701 // Failed to deduct moral Degrade = -1200 // Filtered request due to degradation RPCNoClient = -1201 // No available client for rpc service RPCNoAuth = -1202 // Client for rpc service not authorized )
Define all error codes
Functions ¶
func AlreadyExist ¶
AlreadyExist returns already exist message
func AssertionFailed ¶
AssertionFailed returns type assertion failed message
func FieldIsInvalid ¶
FieldIsInvalid returns field invalid message
func FieldIsRequired ¶
FieldIsRequired returns field required message
func Text ¶
Text returns the text corresponding to the error code. If the error code does not exist, it returns a default message.
func TypeMismatch ¶
TypeMismatch returns type mismatch message
Types ¶
This section is empty.