errors.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package errorx
  15. import "fmt"
  16. type ErrorCode int
  17. const (
  18. GENERAL_ERR ErrorCode = iota
  19. NOT_FOUND
  20. )
  21. const IOErr = "io error"
  22. var NotFoundErr = NewWithCode(NOT_FOUND, "not found")
  23. type Error struct {
  24. msg string
  25. code ErrorCode
  26. }
  27. func New(message string) *Error {
  28. return &Error{message, GENERAL_ERR}
  29. }
  30. func NewWithCode(code ErrorCode, message string) *Error {
  31. return &Error{message, code}
  32. }
  33. func (e *Error) Error() string {
  34. return e.msg
  35. }
  36. func (e *Error) Code() ErrorCode {
  37. return e.code
  38. }
  39. type MultiError map[string]error
  40. func (e MultiError) Error() string {
  41. var s string
  42. switch len(e) {
  43. case 0, 1:
  44. s = ""
  45. default:
  46. s = "Get multiple errors: "
  47. }
  48. for k, v := range e {
  49. s = fmt.Sprintf("%s\n%s:%s", s, k, v.Error())
  50. }
  51. return s
  52. }
  53. func (e MultiError) GetError() error {
  54. if len(e) > 0 {
  55. return e
  56. }
  57. return nil
  58. }