errors.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. var NotFoundErr = NewWithCode(NOT_FOUND, "not found")
  22. type Error struct {
  23. msg string
  24. code ErrorCode
  25. }
  26. func New(message string) *Error {
  27. return &Error{message, GENERAL_ERR}
  28. }
  29. func NewWithCode(code ErrorCode, message string) *Error {
  30. return &Error{message, code}
  31. }
  32. func (e *Error) Error() string {
  33. return e.msg
  34. }
  35. func (e *Error) Code() ErrorCode {
  36. return e.code
  37. }
  38. type MultiError map[string]error
  39. func (e MultiError) Error() string {
  40. var s string
  41. switch len(e) {
  42. case 0, 1:
  43. s = ""
  44. default:
  45. s = "Get multiple errors: "
  46. }
  47. for k, v := range e {
  48. s = fmt.Sprintf("%s\n%s:%s", s, k, v.Error())
  49. }
  50. return s
  51. }
  52. func (e MultiError) GetError() error {
  53. if len(e) > 0 {
  54. return e
  55. }
  56. return nil
  57. }