errors.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 (
  18. "fmt"
  19. "github.com/ethereum/go-ethereum/logger/glog"
  20. )
  21. /*
  22. Errors implements an error handler providing standardised errors for a package.
  23. Fields:
  24. Errors:
  25. a map from error codes to description
  26. Package:
  27. name of the package/component
  28. */
  29. type Errors struct {
  30. Errors map[int]string
  31. Package string
  32. }
  33. /*
  34. Error implements the standard go error interface.
  35. errors.New(code, format, params ...interface{})
  36. Prints as:
  37. [package] description: details
  38. where details is fmt.Sprintf(self.format, self.params...)
  39. */
  40. type Error struct {
  41. Code int
  42. Name string
  43. Package string
  44. message string
  45. format string
  46. params []interface{}
  47. }
  48. func (self *Errors) New(code int, format string, params ...interface{}) *Error {
  49. name, ok := self.Errors[code]
  50. if !ok {
  51. panic("invalid error code")
  52. }
  53. return &Error{
  54. Code: code,
  55. Name: name,
  56. Package: self.Package,
  57. format: format,
  58. params: params,
  59. }
  60. }
  61. func (self Error) Error() (message string) {
  62. if len(message) == 0 {
  63. self.message = fmt.Sprintf("[%s] ERROR: %s", self.Package, self.Name)
  64. if self.format != "" {
  65. self.message += ": " + fmt.Sprintf(self.format, self.params...)
  66. }
  67. }
  68. return self.message
  69. }
  70. func (self Error) Log(v glog.Verbose) {
  71. if v {
  72. v.Infoln(self)
  73. }
  74. }