Skip to content

Commit

Permalink
[Error] Introduce ErrorBuilder type and AddErrorBuilders() callback.
Browse files Browse the repository at this point in the history
  • Loading branch information
jkuma committed May 30, 2023
1 parent ec2659a commit 968b886
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
27 changes: 27 additions & 0 deletions errors/builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package errors

import (
"sync"
)

var (
// errorBuilders slice contains all custom ErrorBuilder callbacks.
// You can update this list if you want to change ErrorBuilder callbacks
// for all you handlers.
errorBuilders []ErrorBuilder

// addErrorBuildersMU is a sync.Mutex used by AddErrorBuilders.
addErrorBuildersMU sync.Mutex
)

// ErrorBuilder is a callback that transform the given error to a gapi Error.
type ErrorBuilder func(err error) Error

// AddErrorBuilders appends custom errors.ErrorBuilder.
// These callbacks are executed when wrapping an error with errors.Wrap().
func AddErrorBuilders(builders ...ErrorBuilder) {
addErrorBuildersMU.Lock()
defer addErrorBuildersMU.Unlock()

errorBuilders = append(errorBuilders, builders...)
}
6 changes: 6 additions & 0 deletions errors/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ func Wrap(err error) Error {
return nil
}

for _, builder := range errorBuilders {
if gErr := builder(err); gErr != nil {
return gErr
}
}

newErr := &FullError{
userMessage: err.Error(),
kind: "",
Expand Down

0 comments on commit 968b886

Please sign in to comment.