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 ¶
- Constants
- func Wrap(err error, s Status) error
- func WrapCode(err error, code int) error
- func WrapStatus(err error, code int, text string) error
- type CanUnmarshalResponse
- type Describer
- type Detail
- type DetailSetter
- type Err
- type Error
- type HasCodeText
- type HasPointer
- type Modifier
- type Response
- type Status
- type TitleSetter
Examples ¶
Constants ¶
const MediaType = "application/problem+json"
MediaType of error response, see RFC 9457
Variables ¶
This section is empty.
Functions ¶
Types ¶
type CanUnmarshalResponse ¶
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 ¶
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 ¶
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 ¶
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) StatusCode ¶
func (*Detail) StatusText ¶
type DetailSetter ¶
type DetailSetter interface {
SetDetail(detail string)
}
type Err ¶
type Err struct {
// contains filtered or unexported fields
}
func (*Err) StatusCode ¶
func (*Err) StatusText ¶
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 ¶
HasPointer presents error position by a JSON Pointer (RFC 6901) in the request document, see Detail.Pointer
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 ¶
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) SetStatusCode ¶
SetStatusCode overrides status code, see Modifier
func (*Response) StatusCode ¶
func (*Response) StatusText ¶
type Status ¶
type Status interface {
Describer
HasCodeText
IsValid() bool
}
type TitleSetter ¶
type TitleSetter interface {
SetTitle(title string)
}