status

package
v1.0.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 9 Imported by: 0 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 status resolves errors into RFC 9457 style problem details.

Response is the root written to the client; it is the exposed subset of Detail, the full problem that travels as an error. They stay separate types so that the exposed surface can hide more in the future.

Resolution

AsResponse and AsDetail walk an error chain from outside in, and resolve two things independently, each from the first node providing it:

  • status: the first node declaring a status code (> 0), such as Wrap/WrapCode or a codex code declaring `@code api`. nodes declaring nothing are skipped. without any declaration it is 400 for errors located in the request (HasPointer), otherwise 500.
  • identity layer: the outermost codex.Error. code, key, title and detail come from it only: code is codex.Error.Code, key is the code identifier, title is the code hint and detail is codex.Error.Detail (the format and args of codex.Errorf / codex.Wrapf). fields it lacks are left empty; they are neither looked up from inner nodes nor filled with the status text.

Each branch of errors.Join becomes an entry of Errors: branches inherit the status above the Join and resolve their own identity layer. The top level of Response takes the identity layer above the Join if any, otherwise the first entry. A downstream *Detail in the chain is kept as an entry as is.

Exposure

The full text of an error (codex messages, causes, Error() of plain errors) is kept in Desc, which is never serialized (`json:"-"`) and only serves logging. Response bodies carry no `type`, `status` or `instance`: the status is in the status line, the identity is `key` and the source is the `Server` response header.

Index

Examples

Constants

View Source
const MediaType = "application/problem+json"

MediaType of error response, see RFC 9457

Variables

This section is empty.

Functions

func Wrap

func Wrap(err error, s Status) error

func WrapCode

func WrapCode(err error, code int) error

func WrapStatus

func WrapStatus(err error, code int, text string) error

Types

type CanUnmarshalResponse

type CanUnmarshalResponse interface {
	UnmarshalResponse(code int, data []byte) error
}

type Describer

type Describer interface {
	StatusCode() int
}

type Detail

type Detail struct {
	// Code biz error code
	Code int64 `json:"code,omitzero"`
	// Key code identifier
	Key string `json:"key,omitzero"`
	// Title code hint, the same for every occurrence of the problem
	Title string `json:"title,omitzero"`
	// Detail explanation of this occurrence, for client not for debugging
	Detail string `json:"detail,omitzero"`
	// Pointer JSON Pointer (RFC 6901) to the error position in the request
	// document. the document roots are payload.Locations, eg: `/body/items/0/age`,
	// `/query/ids/1`, `/header/X-Request-Id`. the pointer of a downstream Detail
	// is relative to the downstream request.
	Pointer jsontext.Pointer `json:"pointer,omitzero"`
	// Src caused source. eg: srv-abc@v0.0.1
	Src string `json:"src,omitzero"`
	// Desc the full text of the error, for logging only, never presented
	Desc string `json:"-"`
	// Errors sub problems from downstream
	Errors []*Detail `json:"errors,omitzero"`

	// Status http status code, 0 means unspecified (eg: downstream sub problems)
	Status int `json:"-"`
}

Detail is an item of problem details. json fields follow RFC 9457 where the semantics match; the others are extension members.

func AsDetail

func AsDetail(err error, src string) *Detail

AsDetail resolves err as a single problem: the status is the first declared one from outside in, and code, key, title and detail come from the outermost codex error (the identity layer) only. a downstream *Detail is returned as is.

Example
// domain code wraps a cause: code, key, title and detail come from the domain code
OutputDetail(status.AsDetail(codex.Wrapf(USER__NOT_FOUND, errors.New("sql: no rows"), "user %d not found", 9), "srv"))

// plain error with an explicit status: no identity layer
OutputDetail(status.AsDetail(status.WrapCode(errors.New("some error"), http.StatusServiceUnavailable), "srv"))

// plain error: 500
OutputDetail(status.AsDetail(errors.New("UnknownError"), "srv"))

// request located error: 400
OutputDetail(status.AsDetail(validation.PrefixPointer(validation.WrapPointer(errors.New("e3"), "/items/0/age"), "/body"), "srv"))
Output:
USER::NOT_FOUND{user 9 not found}
  title:   用户不存在
  code:    404
SERVICE_UNAVAILABLE{SERVICE_UNAVAILABLE{message="some error",status=503}}
  code:    503
INTERNAL_SERVER_ERROR{UnknownError}
  code:    500
BAD_REQUEST{e3: [pointer:/body/items/0/age]}
  pointer: /body/items/0/age
  code:    400

func UnmarshalResponse

func UnmarshalResponse(code int, rspraw []byte) *Detail

UnmarshalResponse parses an error body from a downstream service. The body is expected to be a Response (RFC 9457 style problem details). msg and message are compatible with the common {code, msg} style error body. A non JSON body is kept in Detail and the status code turns to 500.

Example
package main

import (
	"encoding/json/v2"
	"fmt"
	"net/http"

	"github.com/xoctopus/httpx/internal/status"
)

func main() {
	// RFC 9457 style problem details, sub problems are kept in errors
	rspraw, _ := json.Marshal(status.Response{
		Key:    "AUTH__INVALID_USERNAME",
		Code:   1,
		Title:  "用户名不合法",
		Detail: "请输入8-16位, 以应为字母开头且仅包含英文字符和数字",
		Errors: []*status.Detail{{
			Key:     "BAD_REQUEST",
			Pointer: "/body/username",
			Src:     "srv-auth-gateway@v0.0.1",
			Status:  http.StatusBadRequest,
		}},
	})
	de := status.UnmarshalResponse(http.StatusBadRequest, rspraw)
	OutputDetail(de)
	OutputDetail(de.Errors[0])

	// compatible with {code, msg} and {message}
	de = status.UnmarshalResponse(http.StatusUnauthorized, []byte(`{"code":2,"msg":"未登录"}`))
	OutputDetail(de)
	de = status.UnmarshalResponse(http.StatusUnauthorized, []byte(`{"message":"未登录"}`))
	OutputDetail(de)

	// empty body
	de = status.UnmarshalResponse(http.StatusNotFound, []byte(`{}`))
	OutputDetail(de)
	de = status.UnmarshalResponse(http.StatusNotFound, nil)
	OutputDetail(de)

	// non JSON body
	de = status.UnmarshalResponse(http.StatusBadRequest, []byte("用户名不合法"))
	OutputDetail(de)

}

func OutputDetail(de *status.Detail) {
	fmt.Println(de)
	if len(de.Title) > 0 {
		fmt.Println("  title:  ", de.Title)
	}
	if len(de.Pointer) > 0 {
		fmt.Println("  pointer:", de.Pointer)
	}
	fmt.Println("  code:   ", de.StatusCode())
}
Output:
AUTH__INVALID_USERNAME{请输入8-16位, 以应为字母开头且仅包含英文字符和数字}
  title:   用户名不合法
  code:    400
BAD_REQUEST{}
  pointer: /body/username
  code:    0
UNAUTHORIZED{未登录}
  title:   未登录
  code:    401
UNAUTHORIZED{未登录}
  title:   未登录
  code:    401
NOT_FOUND{Not Found}
  title:   Not Found
  code:    404
NOT_FOUND{Not Found}
  title:   Not Found
  code:    404
INTERNAL_SERVER_ERROR{用户名不合法}
  title:   Internal Server Error
  code:    500

func (*Detail) Error

func (d *Detail) Error() string

Error is for logging: the key, or the status text when there is no key, with the first of detail, title and desc.

func (*Detail) SetDetail

func (d *Detail) SetDetail(detail string)

func (*Detail) StatusCode

func (d *Detail) StatusCode() int

func (*Detail) StatusText

func (d *Detail) StatusText() string

func (*Detail) UnmarshalResponse

func (d *Detail) UnmarshalResponse(code int, data []byte) error

UnmarshalResponse keeps Src if it is set by caller, eg: downstream host.

type DetailSetter

type DetailSetter interface {
	SetDetail(detail string)
}

type Err

type Err struct {
	// contains filtered or unexported fields
}

func (*Err) Error

func (e *Err) Error() string

func (*Err) StatusCode

func (e *Err) StatusCode() int

func (*Err) StatusText

func (e *Err) StatusText() string

func (*Err) Unwrap

func (e *Err) Unwrap() error

type Error

type Error interface {
	Describer
	HasCodeText
	error
}

type HasCodeText

type HasCodeText interface {
	// StatusText returns code text. eg: http.StatusOK => http.StatusText(http.StatusOK)
	StatusText() string
}

type HasPointer

type HasPointer interface {
	Pointer() jsontext.Pointer
}

HasPointer presents error position by a JSON Pointer (RFC 6901) in the request document, see Detail.Pointer

type Modifier

type Modifier interface {
	SetStatusCode(int)
}

type Response

type Response struct {
	// Code biz code
	Code int64 `json:"code,omitzero"`
	// Key code identifier
	Key string `json:"key,omitzero"`
	// Title code hint, the same for every occurrence of the problem
	Title string `json:"title,omitzero"`
	// Detail explanation of this occurrence, for client not for debugging
	Detail string `json:"detail,omitzero"`
	// Errors problems occurred in the same request
	Errors []*Detail `json:"errors,omitzero"`

	// Desc the full text of the error, for logging only, never presented
	Desc string `json:"-"`
	// contains filtered or unexported fields
}

Response is the root of problem details. json fields follow RFC 9457 where the semantics match; the others are extension members. status and instance are not serialized: http status code is in status line, and the operation is identified by `Server` header.

func AsResponse

func AsResponse(err error, src string) *Response

AsResponse resolves err as the root of problem details. the top level takes the identity layer above errors.Join if any, otherwise the first entry.

func (*Response) SetDetail

func (e *Response) SetDetail(detail string)

func (*Response) SetStatusCode

func (e *Response) SetStatusCode(code int)

SetStatusCode overrides status code, see Modifier

func (*Response) SetTitle

func (e *Response) SetTitle(title string)

func (*Response) StatusCode

func (e *Response) StatusCode() int

func (*Response) StatusText

func (e *Response) StatusText() string

func (*Response) Unwrap

func (e *Response) Unwrap() []error

type Status

type Status interface {
	Describer
	HasCodeText

	IsValid() bool
}

func AsStatus

func AsStatus(code int) Status

type TitleSetter

type TitleSetter interface {
	SetTitle(title string)
}

Jump to

Keyboard shortcuts

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