You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

error.go 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package util
  4. import (
  5. "errors"
  6. "fmt"
  7. )
  8. // Common Errors forming the base of our error system
  9. //
  10. // Many Errors returned by Gitea can be tested against these errors
  11. // using errors.Is.
  12. var (
  13. ErrInvalidArgument = errors.New("invalid argument")
  14. ErrPermissionDenied = errors.New("permission denied")
  15. ErrAlreadyExist = errors.New("resource already exists")
  16. ErrNotExist = errors.New("resource does not exist")
  17. )
  18. // SilentWrap provides a simple wrapper for a wrapped error where the wrapped error message plays no part in the error message
  19. // Especially useful for "untyped" errors created with "errors.New(…)" that can be classified as 'invalid argument', 'permission denied', 'exists already', or 'does not exist'
  20. type SilentWrap struct {
  21. Message string
  22. Err error
  23. }
  24. // Error returns the message
  25. func (w SilentWrap) Error() string {
  26. return w.Message
  27. }
  28. // Unwrap returns the underlying error
  29. func (w SilentWrap) Unwrap() error {
  30. return w.Err
  31. }
  32. // NewSilentWrapErrorf returns an error that formats as the given text but unwraps as the provided error
  33. func NewSilentWrapErrorf(unwrap error, message string, args ...interface{}) error {
  34. if len(args) == 0 {
  35. return SilentWrap{Message: message, Err: unwrap}
  36. }
  37. return SilentWrap{Message: fmt.Sprintf(message, args...), Err: unwrap}
  38. }
  39. // NewInvalidArgumentErrorf returns an error that formats as the given text but unwraps as an ErrInvalidArgument
  40. func NewInvalidArgumentErrorf(message string, args ...interface{}) error {
  41. return NewSilentWrapErrorf(ErrInvalidArgument, message, args...)
  42. }
  43. // NewPermissionDeniedErrorf returns an error that formats as the given text but unwraps as an ErrPermissionDenied
  44. func NewPermissionDeniedErrorf(message string, args ...interface{}) error {
  45. return NewSilentWrapErrorf(ErrPermissionDenied, message, args...)
  46. }
  47. // NewAlreadyExistErrorf returns an error that formats as the given text but unwraps as an ErrAlreadyExist
  48. func NewAlreadyExistErrorf(message string, args ...interface{}) error {
  49. return NewSilentWrapErrorf(ErrAlreadyExist, message, args...)
  50. }
  51. // NewNotExistErrorf returns an error that formats as the given text but unwraps as an ErrNotExist
  52. func NewNotExistErrorf(message string, args ...interface{}) error {
  53. return NewSilentWrapErrorf(ErrNotExist, message, args...)
  54. }