-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_response.go
More file actions
47 lines (41 loc) · 1.72 KB
/
error_response.go
File metadata and controls
47 lines (41 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package restapi
// ErrorResponse is the per-error element embedded in the [ResponseBody]
// Errors slice. Only Code is always serialised; Message and Details are
// omitted when empty.
type ErrorResponse struct {
// Code is the application error code, the same value as
// [ErrorRegistryEntry.ErrorCode].
Code int `json:"code"`
// Message is the human-readable explanation. It defaults to the message
// from the matching registry entry and may be overridden per response
// with [WithMessage].
Message string `json:"message,omitempty"`
// Details is optional structured data attached to the error — typically
// field-level validation failures. Populated via [WithDetails].
Details any `json:"details,omitempty"`
}
// NewError builds an [ErrorResponse] for errorCode using the API's registry
// and applies any options. Unknown codes resolve to the registry's fallback
// entry.
func (a *API) NewError(errorCode int, opts ...ErrorOption) ErrorResponse {
entry, _ := a.registry.Lookup(errorCode)
return buildErrorResponse(entry, opts...)
}
// NewError is a convenience wrapper around [API.NewError] that operates on
// [Default].
func NewError(errorCode int, opts ...ErrorOption) ErrorResponse {
return Default().NewError(errorCode, opts...)
}
// buildErrorResponse seeds an [ErrorResponse] from an already-resolved
// [ErrorRegistryEntry] and applies opts. It is the shared core of
// [API.NewError], [API.Error], and [API.Abort]; call sites resolve the
// entry once and pass it in, avoiding a second registry lookup.
func buildErrorResponse(entry ErrorRegistryEntry, opts ...ErrorOption) ErrorResponse {
errorResponse := entry.Response()
for _, opt := range opts {
if opt != nil {
opt(&errorResponse)
}
}
return errorResponse
}