error.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gob
  5. import "fmt"
  6. // Errors in decoding and encoding are handled using panic and recover.
  7. // Panics caused by user error (that is, everything except run-time panics
  8. // such as "index out of bounds" errors) do not leave the file that caused
  9. // them, but are instead turned into plain error returns. Encoding and
  10. // decoding functions and methods that do not return an error either use
  11. // panic to report an error or are guaranteed error-free.
  12. // A gobError is used to distinguish errors (panics) generated in this package.
  13. type gobError struct {
  14. err error
  15. }
  16. // errorf is like error_ but takes Printf-style arguments to construct an error.
  17. // It always prefixes the message with "gob: ".
  18. func errorf(format string, args ...any) {
  19. error_(fmt.Errorf("gob: "+format, args...))
  20. }
  21. // error wraps the argument error and uses it as the argument to panic.
  22. func error_(err error) {
  23. panic(gobError{err})
  24. }
  25. // catchError is meant to be used as a deferred function to turn a panic(gobError) into a
  26. // plain error. It overwrites the error return of the function that deferred its call.
  27. func catchError(err *error) {
  28. if e := recover(); e != nil {
  29. ge, ok := e.(gobError)
  30. if !ok {
  31. panic(e)
  32. }
  33. *err = ge.err
  34. }
  35. }