fix: inherit App error catalogs on generated routes without local errors
This commit is contained in:
@@ -80,3 +80,22 @@ func TestCatalogWrapperPreservesScope(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyCatalogIsTransparent(t *testing.T) {
|
||||
formatter := response.MustNew(response.Config{CodeType: "int32", SuccessCode: 0, ErrorCode: 9999, MessageField: "msg", DataMode: "always"})
|
||||
for _, inner := range []response.Encoder{formatter, response.RawJSON(formatter)} {
|
||||
wrapped, err := response.WithErrors(apierrors.Catalog{}, inner)
|
||||
if err != nil || wrapped != inner {
|
||||
t.Fatal("empty catalog introduced a route policy", err)
|
||||
}
|
||||
// Context resolved this through the App. Original Err must not cause a
|
||||
// second lookup to replace its status, public code or rendered message.
|
||||
payload, err := wrapped.Encode(response.Result{Status: 400, Code: "INVALID", BusinessCode: int64(400002), Message: "项目提示", Failed: true, Err: apierrors.ByCode("INVALID")})
|
||||
if err != nil || payload.Status != 400 || !strings.Contains(string(payload.Body), "项目提示") {
|
||||
t.Fatal(payload, err)
|
||||
}
|
||||
}
|
||||
if _, err := response.WithErrors(apierrors.Catalog{DefaultStatus: 204}, formatter); err == nil {
|
||||
t.Fatal("invalid empty catalog bypassed validation")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,9 @@ func (e *errorEncoder) Encode(r Result) (Payload, error) {
|
||||
|
||||
// WithErrors binds a catalog to an encoder without imposing a response shape.
|
||||
// Built-in templates are checked for incompatible code types and conflicting
|
||||
// legacy mappings. Custom encoders remain responsible for their wire contract.
|
||||
// legacy mappings. An empty catalog leaves next unchanged, so Context can
|
||||
// inherit its App catalog without a second, empty lookup during encoding.
|
||||
// Custom encoders remain responsible for their wire contract.
|
||||
func WithErrors(catalog apierrors.Catalog, next Encoder) (Encoder, error) {
|
||||
registry, err := apierrors.NewRegistry(catalog)
|
||||
if err != nil {
|
||||
@@ -35,10 +37,10 @@ func WithErrors(catalog apierrors.Catalog, next Encoder) (Encoder, error) {
|
||||
if next == nil {
|
||||
next = Default()
|
||||
}
|
||||
if len(catalog.Definitions) == 0 {
|
||||
return next, nil
|
||||
}
|
||||
if provider, ok := next.(ErrorRegistryProvider); ok && provider.ErrorRegistry() != nil {
|
||||
if len(catalog.Definitions) == 0 {
|
||||
return next, nil
|
||||
}
|
||||
if reflect.DeepEqual(registry.Catalog(), provider.ErrorRegistry().Catalog()) {
|
||||
return next, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user