github.com/blend/go-sdk@v1.20220411.3/async/recover.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package async 9 10 import ( 11 "sync" 12 13 "github.com/blend/go-sdk/ex" 14 ) 15 16 /* 17 Recover runs an action and passes any errors to the given errors channel. 18 19 This call blocks, if you need it to be backgrounded, you should call it like: 20 21 go Recover(action, errors) 22 <-errors 23 */ 24 func Recover(action func() error, errors chan error) { 25 defer func() { 26 if r := recover(); r != nil && errors != nil { 27 errors <- ex.New(r) 28 } 29 }() 30 31 if err := action(); err != nil && errors != nil { 32 errors <- err 33 } 34 } 35 36 // RecoverGroup runs a recovery against a specific wait group with an error collector. 37 // It calls Recover internally. 38 func RecoverGroup(action func() error, errors chan error, wg *sync.WaitGroup) { 39 Recover(func() error { 40 if wg != nil { 41 defer wg.Done() 42 } 43 return action() 44 }, errors) 45 }