errors.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package errs
  17. import "fmt"
  18. /*
  19. Errors implements an error handler providing standardised errors for a package.
  20. Fields:
  21. Errors:
  22. a map from error codes to description
  23. Package:
  24. name of the package/component
  25. */
  26. type Errors struct {
  27. Errors map[int]string
  28. Package string
  29. }
  30. /*
  31. Error implements the standard go error interface.
  32. errors.New(code, format, params ...interface{})
  33. Prints as:
  34. [package] description: details
  35. where details is fmt.Sprintf(self.format, self.params...)
  36. */
  37. type Error struct {
  38. Code int
  39. Name string
  40. Package string
  41. message string
  42. format string
  43. params []interface{}
  44. }
  45. func (self *Errors) New(code int, format string, params ...interface{}) *Error {
  46. name, ok := self.Errors[code]
  47. if !ok {
  48. panic("invalid error code")
  49. }
  50. return &Error{
  51. Code: code,
  52. Name: name,
  53. Package: self.Package,
  54. format: format,
  55. params: params,
  56. }
  57. }
  58. func (self Error) Error() (message string) {
  59. if len(message) == 0 {
  60. self.message = fmt.Sprintf("[%s] ERROR: %s", self.Package, self.Name)
  61. if self.format != "" {
  62. self.message += ": " + fmt.Sprintf(self.format, self.params...)
  63. }
  64. }
  65. return self.message
  66. }