From 8601f0f98c426aa5bb9285f97ca3a37aa6936f72 Mon Sep 17 00:00:00 2001 From: Alex Guerrieri Date: Wed, 4 Dec 2024 14:12:04 +0100 Subject: [PATCH] Error by Code/Name --- _examples/golang-basics/example.gen.go | 32 ++++++++++++++++++++++++++ errors.go.tmpl | 20 ++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/_examples/golang-basics/example.gen.go b/_examples/golang-basics/example.gen.go index 9d979f9..1064df5 100644 --- a/_examples/golang-basics/example.gen.go +++ b/_examples/golang-basics/example.gen.go @@ -1055,3 +1055,35 @@ var ( ErrUnauthorized = WebRPCError{Code: 400200, Name: "Unauthorized", Message: "unauthorized", HTTPStatus: 401} ErrUserNotFound = WebRPCError{Code: 400300, Name: "UserNotFound", Message: "user not found", HTTPStatus: 400} ) + +func ErrorByCode(code int) (WebRPCError, bool) { + switch code { + case ErrMissingArgument.Code: + return ErrMissingArgument, true + case ErrInvalidUsername.Code: + return ErrInvalidUsername, true + case ErrMemoryFull.Code: + return ErrMemoryFull, true + case ErrUnauthorized.Code: + return ErrUnauthorized, true + case ErrUserNotFound.Code: + return ErrUserNotFound, true + } + return WebRPCError{}, false +} + +func ErrorByName(name string) (WebRPCError, bool) { + switch name { + case ErrMissingArgument.Name: + return ErrMissingArgument, true + case ErrInvalidUsername.Name: + return ErrInvalidUsername, true + case ErrMemoryFull.Name: + return ErrMemoryFull, true + case ErrUnauthorized.Name: + return ErrUnauthorized, true + case ErrUserNotFound.Name: + return ErrUserNotFound, true + } + return WebRPCError{}, false +} diff --git a/errors.go.tmpl b/errors.go.tmpl index e409369..087cee2 100644 --- a/errors.go.tmpl +++ b/errors.go.tmpl @@ -91,6 +91,26 @@ var ( {{ printf "Err%s = WebRPCError{Code: %v, Name: %q, Message: %q, HTTPStatus: %v}" $error.Name $error.Code $error.Name $error.Message $error.HTTPStatus}} {{- end}} ) + +func ErrorByCode(code int) (WebRPCError, bool) { + switch code { + {{- range $_, $error := $schemaErrors}} + case Err{{$error.Name}}.Code: + return Err{{$error.Name}}, true + {{- end}} + } + return WebRPCError{}, false +} + +func ErrorByName(name string) (WebRPCError, bool) { + switch name { + {{- range $_, $error := $schemaErrors}} + case Err{{$error.Name}}.Name: + return Err{{$error.Name}}, true + {{- end}} + } + return WebRPCError{}, false +} {{ end -}} {{- end -}}