safeerror

package
v0.2.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
const StatusClientClosedRequest = 499

StatusClientClosedRequest is the nginx convention for a client that disconnected before the response was written.

Variables

View Source
var (
	ErrValidation      = &SafeError{Code: CodeValidation}
	ErrUnauthorized    = &SafeError{Code: CodeUnauthorized}
	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

func Report(ctx context.Context, err error, attrs ...any) *dto.ResponseMessage

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"
	CodeUnauthorized    Code = "UNAUTHORIZED"
	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

func (c Code) DefaultMessage() string

DefaultMessage returns the default user message for c.

func (Code) HTTPStatus

func (c Code) HTTPStatus() int

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

func Canceled(err error) *SafeError

Canceled reports a request canceled by the client. A context.Canceled is best returned unchanged: Classify maps it to CANCELED by itself.

func Conflict

func Conflict(msg string, err error) *SafeError

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

func Database(err error) *SafeError

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 External

func External(err error) *SafeError

External hides a failure of another service or downstream HTTP API.

func Forbidden

func Forbidden(msg string, err error) *SafeError

Forbidden reports that the caller lacks permission.

func Internal

func Internal(err error) *SafeError

Internal hides an unexpected failure.

func LLM

func LLM(err error) *SafeError

LLM hides an AI provider failure.

func New

func New(code Code, userMsg string, internal error) *SafeError

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

func NotFound(msg string, err error) *SafeError

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

func QuotaExceeded(msg string, err error) *SafeError

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

func Timeout(err error) *SafeError

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

func Unauthorized(msg string, err error) *SafeError

Unauthorized reports a missing or invalid authentication.

func Validation

func Validation(msg string, err error) *SafeError

Validation reports invalid input.

func VersionConflict

func VersionConflict(msg string, err error) *SafeError

VersionConflict reports an optimistic-lock (stale revision) conflict.

func (*SafeError) Error

func (e *SafeError) Error() string

Error returns only the user message, so Internal can never leak via Error().

func (*SafeError) Is

func (e *SafeError) Is(target error) bool

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

func (*SafeError) LogString

func (e *SafeError) LogString() string

LogString returns the full context for internal logs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL