Documentation
¶
Overview ¶
Package safeerror separates the message a client may see from the internal cause that only logs may see. A *SafeError's Error() returns only UserMsg, and it deliberately has no Unwrap(), so the internal cause cannot leak through err.Error() or be reached by errors.Is/errors.As.
Index ¶
- Constants
- Variables
- func Classify(err error) (resp *dto.ResponseMessage, logLine string)
- func Report(ctx context.Context, err error, attrs ...any) *dto.ResponseMessage
- type Code
- type SafeError
- func Canceled(err error) *SafeError
- func Conflict(msg string, err error) *SafeError
- func Database(err error) *SafeError
- func External(err error) *SafeError
- func Forbidden(msg string, err error) *SafeError
- func Internal(err error) *SafeError
- func LLM(err error) *SafeError
- func New(code Code, userMsg string, internal error) *SafeError
- func NotFound(msg string, err error) *SafeError
- func QuotaExceeded(msg string, err error) *SafeError
- func Timeout(err error) *SafeError
- func Unauthorized(msg string, err error) *SafeError
- func Validation(msg string, err error) *SafeError
- func VersionConflict(msg string, err error) *SafeError
Examples ¶
Constants ¶
const StatusClientClosedRequest = 499
StatusClientClosedRequest is the nginx convention for a client that disconnected before the response was written.
Variables ¶
var ( ErrValidation = &SafeError{Code: CodeValidation} ErrForbidden = &SafeError{Code: CodeForbidden} ErrNotFound = &SafeError{Code: CodeNotFound} ErrConflict = &SafeError{Code: CodeConflict} ErrVersionConflict = &SafeError{Code: CodeVersionConflict} ErrQuotaExceeded = &SafeError{Code: CodeQuotaExceeded} ErrCanceled = &SafeError{Code: CodeCanceled} ErrDatabase = &SafeError{Code: CodeDatabase} ErrInternal = &SafeError{Code: CodeInternal} ErrExternal = &SafeError{Code: CodeExternal} ErrLLM = &SafeError{Code: CodeLLM} ErrTimeout = &SafeError{Code: CodeTimeout} )
Sentinels for errors.Is comparison. Never return them directly: they carry no Internal. Use the constructors instead.
Functions ¶
func Classify ¶
func Classify(err error) (resp *dto.ResponseMessage, logLine string)
Classify turns any error into a safe response and a log line. A *SafeError keeps its own Code and message; other errors get a best-effort Code with the default message. Unrecognized errors and unknown Codes (a Code not defined in this package) become INTERNAL: less detail, never a leak; the original Code stays in the log line. The response is a fresh value on every call.
Example ¶
ExampleClassify shows the fallback for errors that nobody translated: known kinds get a matching code, anything else becomes INTERNAL. The message is always the default one, never the raw error text.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
func main() {
for _, err := range []error{
fmt.Errorf("query: %w", context.Canceled),
context.DeadlineExceeded,
sql.ErrNoRows,
errors.New("panic: runtime error: index out of range [3] with length 2"),
} {
resp, _ := safeerror.Classify(err)
fmt.Println(resp.Code, resp.ErrorCode, resp.Message)
}
}
Output: 499 CANCELED request canceled 504 TIMEOUT request timed out, please retry later 404 NOT_FOUND record not found 500 INTERNAL internal server error
func Report ¶
Report classifies err, logs the full detail and returns the safe response. It holds the framework-independent part of an HTTP error response: a web framework adapter (such as gin.Respond) adds its request attrs and writes the returned response. A 5xx is logged at error level, any other status (4xx, including 499 for a canceled request) at warn level. Report returns nil and logs nothing when err is nil.
Types ¶
type Code ¶
type Code string
Code is the machine-readable error kind sent to clients as "errorCode".
const ( CodeValidation Code = "VALIDATION" CodeForbidden Code = "FORBIDDEN" CodeNotFound Code = "NOT_FOUND" CodeConflict Code = "CONFLICT" CodeVersionConflict Code = "VERSION_CONFLICT" CodeQuotaExceeded Code = "QUOTA_EXCEEDED" CodeCanceled Code = "CANCELED" CodeDatabase Code = "DATABASE" CodeInternal Code = "INTERNAL" CodeExternal Code = "EXTERNAL" CodeLLM Code = "LLM" CodeTimeout Code = "TIMEOUT" )
func (Code) DefaultMessage ¶
DefaultMessage returns the default user message for c.
func (Code) HTTPStatus ¶
HTTPStatus returns the HTTP status for c; unknown codes map to 500.
Example ¶
ExampleCode_HTTPStatus shows the fixed mapping from Code to HTTP status.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
func main() {
for _, c := range []safeerror.Code{
safeerror.CodeValidation,
safeerror.CodeQuotaExceeded,
safeerror.CodeExternal,
} {
fmt.Println(c, c.HTTPStatus(), c.DefaultMessage())
}
}
Output: VALIDATION 400 invalid request QUOTA_EXCEEDED 429 quota exceeded, please retry later EXTERNAL 502 dependent service unavailable, please retry later
type SafeError ¶
type SafeError struct {
Code Code // machine-readable kind, sent to the client
UserMsg string // safe English message, sent to the client
Internal error // raw cause; logged only, never sent
}
SafeError carries a user-safe message and an internal cause, kept apart. Put log context (ids, keys) into Internal with fmt.Errorf("...: %w", err).
func Canceled ¶
Canceled reports a request canceled by the client. A context.Canceled is best returned unchanged: Classify maps it to CANCELED by itself.
func Conflict ¶
Conflict reports a conflict with the current state, e.g. a business rule.
Example ¶
ExampleConflict shows a business error made by the service layer. Its message is written by the developer and is safe to show.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
func main() {
err := safeerror.Conflict("cannot delete product: it still has active features", nil)
resp, _ := safeerror.Classify(err)
fmt.Println(resp.Code, resp.ErrorCode, resp.Message)
}
Output: 409 CONFLICT cannot delete product: it still has active features
func Database ¶
Database hides a database failure.
Example ¶
ExampleDatabase shows that a database error never reaches the client: the message is generic, the driver error goes to the log line only.
package main
import (
"errors"
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
func main() {
driverErr := errors.New(`pq: relation "secret_table" does not exist`)
err := safeerror.Database(fmt.Errorf("get article 7: %w", driverErr))
resp, logLine := safeerror.Classify(err)
fmt.Println(resp.Code, resp.ErrorCode, resp.Message)
fmt.Println(logLine)
}
Output: 500 DATABASE database error, please retry later code=DATABASE msg="database error, please retry later" internal=get article 7: pq: relation "secret_table" does not exist
func New ¶
New builds a SafeError of any Code; an empty userMsg falls back to the code's default. Each Code also has its own constructor below.
func NotFound ¶
NotFound reports a missing record, e.g. NotFound("article not found", nil).
Example ¶
ExampleNotFound shows that Error() returns only the user message, while the internal cause stays for the log.
package main
import (
"database/sql"
"errors"
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
// getArticle stands for a service method that wants a specific message. A
// dao returns the raw error; Classify alone would report "record not found".
func getArticle(id int64) error {
err := sql.ErrNoRows
if errors.Is(err, sql.ErrNoRows) {
return safeerror.NotFound("article not found", fmt.Errorf("get article %d: %w", id, err))
}
return err
}
func main() {
err := getArticle(7)
fmt.Println(err.Error())
var se *safeerror.SafeError
if errors.As(err, &se) {
fmt.Println(se.Code, se.Internal)
}
}
Output: article not found NOT_FOUND get article 7: sql: no rows in result set
func QuotaExceeded ¶
QuotaExceeded reports that the caller used up a quota.
Example ¶
ExampleQuotaExceeded shows a module-specific error built from a shared Code.
package main
import (
"errors"
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
// errUploadQuota is a module's own business error, built from a shared Code.
// It lives in the module, not in this package.
var errUploadQuota = safeerror.QuotaExceeded("too many upload URLs in 24 hours", nil)
func main() {
resp, _ := safeerror.Classify(fmt.Errorf("upload: %w", errUploadQuota))
fmt.Println(resp.Code, resp.ErrorCode, resp.Message)
fmt.Println(errors.Is(errUploadQuota, safeerror.ErrQuotaExceeded))
}
Output: 429 QUOTA_EXCEEDED too many upload URLs in 24 hours true
func Timeout ¶
Timeout reports an operation that ran out of time, e.g. a downstream call. A context.DeadlineExceeded is best returned unchanged: Classify maps it to TIMEOUT by itself.
func Unauthorized ¶
Unauthorized reports a missing or invalid authentication.
func Validation ¶
Validation reports invalid input.
func VersionConflict ¶
VersionConflict reports an optimistic-lock (stale revision) conflict.
func (*SafeError) Error ¶
Error returns only the user message, so Internal can never leak via Error().
func (*SafeError) Is ¶
Is matches by Code only, so errors.Is(err, ErrNotFound) works without exposing Internal.
Example ¶
ExampleSafeError_Is shows how to branch on the error kind. errors.Is matches a SafeError by its Code, also through fmt.Errorf("%w") wrapping, but never reaches the internal cause.
package main
import (
"database/sql"
"errors"
"fmt"
"github.com/phcp-tech/common-library-golang/safeerror"
)
// getArticle stands for a service method that wants a specific message. A
// dao returns the raw error; Classify alone would report "record not found".
func getArticle(id int64) error {
err := sql.ErrNoRows
if errors.Is(err, sql.ErrNoRows) {
return safeerror.NotFound("article not found", fmt.Errorf("get article %d: %w", id, err))
}
return err
}
func main() {
err := fmt.Errorf("service: %w", getArticle(7))
fmt.Println(errors.Is(err, safeerror.ErrNotFound))
fmt.Println(errors.Is(err, safeerror.ErrDatabase))
fmt.Println(errors.Is(err, sql.ErrNoRows)) // opaque: Internal is not reachable
}
Output: true false false