appendinvoke_example_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. package multierr_test
  21. import (
  22. "fmt"
  23. "log"
  24. "os"
  25. "path/filepath"
  26. "go.uber.org/multierr"
  27. )
  28. func ExampleAppendInvoke() {
  29. if err := run(); err != nil {
  30. log.Fatal(err)
  31. }
  32. }
  33. func run() (err error) {
  34. dir, err := os.MkdirTemp("", "multierr")
  35. // We create a temporary directory and defer its deletion when this
  36. // function returns.
  37. //
  38. // If we failed to delete the temporary directory, we append its
  39. // failure into the returned value with multierr.AppendInvoke.
  40. //
  41. // This uses a custom invoker that we implement below.
  42. defer multierr.AppendInvoke(&err, RemoveAll(dir))
  43. path := filepath.Join(dir, "example.txt")
  44. f, err := os.Create(path)
  45. if err != nil {
  46. return err
  47. }
  48. // Similarly, we defer closing the open file when the function returns,
  49. // and appends its failure, if any, into the returned error.
  50. //
  51. // This uses the multierr.Close invoker included in multierr.
  52. defer multierr.AppendInvoke(&err, multierr.Close(f))
  53. if _, err := fmt.Fprintln(f, "hello"); err != nil {
  54. return err
  55. }
  56. return nil
  57. }
  58. // RemoveAll is a multierr.Invoker that deletes the provided directory and all
  59. // of its contents.
  60. type RemoveAll string
  61. func (r RemoveAll) Invoke() error {
  62. return os.RemoveAll(string(r))
  63. }