From 5404cf22ccf89891e7b0980e0000e7feea14ba39 Mon Sep 17 00:00:00 2001 From: franklin Date: Fri, 21 Jul 2023 12:20:14 +0200 Subject: [PATCH] feat: update error docs --- .../gotsrpc/service-interfaces/errors.md | 51 +++++++++++++++++-- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/foomo/docs/projects/gotsrpc/service-interfaces/errors.md b/foomo/docs/projects/gotsrpc/service-interfaces/errors.md index 4d8d6bd..d492c29 100644 --- a/foomo/docs/projects/gotsrpc/service-interfaces/errors.md +++ b/foomo/docs/projects/gotsrpc/service-interfaces/errors.md @@ -1,6 +1,49 @@ # Errors -On the Go server side errors are types, that implement the error type: +Handling errors is always hard and you have to differentiate about some capabilites between server-to-server and server-to-frontend communications: + +## Server to Server + +When using server to server communication you can use the regular go `error` interface. +Since interfaces are not typed but still need to be able to checked on the client side, gotsrpc will wrap them during the encode phase to keep the information using `mapstructure`. + +NOTE: Be aware though, that private attributes on structs will be lost during transportation + +```go +type CustomError struct { + Message string + data string // will be lost +} + +func (e *CustomError) Error() string { + return e.Message +} + +type Service interface { + Do() (err error) +} + +func main() { + // ... + err, clientErr := client.Do() + if clientErr != nil { + panic("client error") + } + + // you will be able to use errors.Is() or errors.As() + var customErr *CustomError + if errors.As(err, &customErr) { + // ... + } + if errors.Is(err, os.ErrExist) { + // ... + } +} +``` + +## Server to Frontend + +On the frontend side, everything needs to be strictly typed so sth like this, does not transport well, since an interface implementation can not be marshalled. ```go // from https://go.dev/blog/error-handling-and-go @@ -9,9 +52,7 @@ type error interface { } ``` -This does not transport well, since an interface implementation can not be marshalled. - -## String Error Types +### String Error Types Scalar string error types provide a nice way to combine Go constants, that translate to TypeScript enums as errors: @@ -43,7 +84,7 @@ export interface ServiceClient { } ``` -## Struct Error Types +### Struct Error Types If an enumeration is not enough and you want to add information to your errors a struct is a good choice (be careful not to expose secrets 😉) :