error.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package soap
  14. import (
  15. "fmt"
  16. "reflect"
  17. "github.com/vmware/govmomi/vim25/types"
  18. )
  19. type regularError struct {
  20. err error
  21. }
  22. func (r regularError) Error() string {
  23. return r.err.Error()
  24. }
  25. type soapFaultError struct {
  26. fault *Fault
  27. }
  28. func (s soapFaultError) Error() string {
  29. msg := s.fault.String
  30. if msg == "" {
  31. if s.fault.Detail.Fault == nil {
  32. msg = "unknown fault"
  33. } else {
  34. msg = reflect.TypeOf(s.fault.Detail.Fault).Name()
  35. }
  36. }
  37. return fmt.Sprintf("%s: %s", s.fault.Code, msg)
  38. }
  39. type vimFaultError struct {
  40. fault types.BaseMethodFault
  41. }
  42. func (v vimFaultError) Error() string {
  43. typ := reflect.TypeOf(v.fault)
  44. for typ.Kind() == reflect.Ptr {
  45. typ = typ.Elem()
  46. }
  47. return typ.Name()
  48. }
  49. func (v vimFaultError) Fault() types.BaseMethodFault {
  50. return v.fault
  51. }
  52. func Wrap(err error) error {
  53. switch err.(type) {
  54. case regularError:
  55. return err
  56. case soapFaultError:
  57. return err
  58. case vimFaultError:
  59. return err
  60. }
  61. return WrapRegularError(err)
  62. }
  63. func WrapRegularError(err error) error {
  64. return regularError{err}
  65. }
  66. func IsRegularError(err error) bool {
  67. _, ok := err.(regularError)
  68. return ok
  69. }
  70. func ToRegularError(err error) error {
  71. return err.(regularError).err
  72. }
  73. func WrapSoapFault(f *Fault) error {
  74. return soapFaultError{f}
  75. }
  76. func IsSoapFault(err error) bool {
  77. _, ok := err.(soapFaultError)
  78. return ok
  79. }
  80. func ToSoapFault(err error) *Fault {
  81. return err.(soapFaultError).fault
  82. }
  83. func WrapVimFault(v types.BaseMethodFault) error {
  84. return vimFaultError{v}
  85. }
  86. func IsVimFault(err error) bool {
  87. _, ok := err.(vimFaultError)
  88. return ok
  89. }
  90. func ToVimFault(err error) types.BaseMethodFault {
  91. return err.(vimFaultError).fault
  92. }