1 // Copyright (c) 2021 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package multierr_test 22 23 import ( 24 "fmt" 25 "log" 26 "os" 27 "path/filepath" 28 29 "go.uber.org/multierr" 30 ) 31 32 func ExampleAppendInvoke() { 33 if err := run(); err != nil { 34 log.Fatal(err) 35 } 36 } 37 38 func run() (err error) { 39 dir, err := os.MkdirTemp("", "multierr") 40 // We create a temporary directory and defer its deletion when this 41 // function returns. 42 // 43 // If we failed to delete the temporary directory, we append its 44 // failure into the returned value with multierr.AppendInvoke. 45 // 46 // This uses a custom invoker that we implement below. 47 defer multierr.AppendInvoke(&err, RemoveAll(dir)) 48 49 path := filepath.Join(dir, "example.txt") 50 f, err := os.Create(path) 51 if err != nil { 52 return err 53 } 54 // Similarly, we defer closing the open file when the function returns, 55 // and appends its failure, if any, into the returned error. 56 // 57 // This uses the multierr.Close invoker included in multierr. 58 defer multierr.AppendInvoke(&err, multierr.Close(f)) 59 60 if _, err := fmt.Fprintln(f, "hello"); err != nil { 61 return err 62 } 63 64 return nil 65 } 66 67 // RemoveAll is a multierr.Invoker that deletes the provided directory and all 68 // of its contents. 69 type RemoveAll string 70 71 func (r RemoveAll) Invoke() error { 72 return os.RemoveAll(string(r)) 73 } 74