github.com/kaydxh/golang@v0.0.131/go/errors/handler.go (about) 1 /* 2 *Copyright (c) 2022, kaydxh 3 * 4 *Permission is hereby granted, free of charge, to any person obtaining a copy 5 *of this software and associated documentation files (the "Software"), to deal 6 *in the Software without restriction, including without limitation the rights 7 *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 *copies of the Software, and to permit persons to whom the Software is 9 *furnished to do so, subject to the following conditions: 10 * 11 *The above copyright notice and this permission notice shall be included in all 12 *copies or substantial portions of the Software. 13 * 14 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 *SOFTWARE. 21 */ 22 package errors 23 24 import ( 25 "context" 26 "time" 27 28 "golang.org/x/time/rate" 29 ) 30 31 // ErrorHandlers is a list of functions which will be invoked when a nonreturnable 32 // error occurs. 33 // should be packaged up into a testable and reusable object. 34 var ErrorHandlers = []func(error){ 35 func() func(err error) { 36 limiter := rate.NewLimiter(rate.Every(time.Millisecond), 1) 37 return func(err error) { 38 // 1ms was the number folks were able to stomach as a global rate limit. 39 // If you need to log errors more than 1000 times a second you 40 // should probably consider fixing your code instead. :) 41 _ = limiter.Wait(context.Background()) 42 } 43 }(), 44 } 45 46 // HandlerError is a method to invoke when a non-user facing piece of code cannot 47 // return an error and needs to indicate it has been ignored. Invoking this method 48 // is preferable to logging the error - the default behavior is to log but the 49 // errors may be sent to a remote server for analysis. 50 func HandleError(err error) { 51 // this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead 52 if err == nil { 53 return 54 } 55 56 for _, fn := range ErrorHandlers { 57 fn(err) 58 } 59 } 60 61 func ErrorChain(handlers ...func(err error, handled bool) (error, bool)) func(err error, handled bool) error { 62 return func(err error, handled bool) error { 63 for _, h := range handlers { 64 if h != nil { 65 err, handled = h(err, handled) 66 } 67 } 68 return err 69 } 70 }