error.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package tos
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. )
  9. var (
  10. InputIsNilClientError = newTosClientError("input is nil. ", nil)
  11. InputInvalidClientError = newTosClientError("input data is invalid. ", nil)
  12. InvalidPartNumber = newTosClientError("input part number is invalid. ", nil)
  13. InvalidUploadID = newTosClientError("input upload id is invalid. ", nil)
  14. InvalidBucketNameLength = newTosClientError("invalid bucket name, the length must be [3, 63]", nil)
  15. InvalidBucketNameCharacter = newTosClientError("invalid bucket name, the character set is illegal", nil)
  16. InvalidBucketNameStartingOrEnding = newTosClientError("invalid bucket name, the bucket name can be neither starting with '-' nor ending with '-'", nil)
  17. InvalidObjectNameLength = newTosClientError("invalid object name, the length must be [1, 696]", nil)
  18. InvalidObjectNameStartingOrEnding = newTosClientError("invalid object name, the object name can not start with '\\'", nil)
  19. InvalidObjectNameCharacterSet = newTosClientError("invalid object name, the character set is illegal", nil)
  20. InvalidACL = newTosClientError("invalid acl type", nil)
  21. InvalidStorageClass = newTosClientError("invalid storage class", nil)
  22. InvalidGrantee = newTosClientError("invalid grantee type", nil)
  23. InvalidCanned = newTosClientError("invalid canned type", nil)
  24. InvalidAzRedundancy = newTosClientError("invalid az redundancy type", nil)
  25. InvalidMetadataDirective = newTosClientError("invalid metadata directive type", nil)
  26. InvalidPermission = newTosClientError("invalid permission type", nil)
  27. InvalidSSECAlgorithm = newTosClientError("invalid encryption-decryption algorithm", nil)
  28. InvalidPartSize = newTosClientError("invalid part size, the size must be [5242880, 5368709120]", nil)
  29. InvalidSrcFilePath = newTosClientError("invalid file path, the file does not exist", nil)
  30. InvalidFilePartNum = newTosClientError("unsupported part number, the maximum is 10000", nil)
  31. InvalidMarshal = newTosClientError("unable to do serialization/deserialization", nil)
  32. InvalidPreSignedURLExpires = newTosClientError("invalid pre signed url expires, the time must be less 604800 seconds.", nil)
  33. InvalidPreSignedConditions = newTosClientError("invalid pre signed url conditions.", nil)
  34. InvalidFilePath = newTosClientError("invalid file path", nil)
  35. InvalidCheckpointFilePath = newTosClientError("invalid checkpoint file path", nil)
  36. CrcCheckFail = newTosClientError("crc check not equal", nil)
  37. InvalidS3Endpoint = newTosClientError("do not support s3 endpoint, please use tos endpoint", nil)
  38. NotSupportSeek = newTosClientError("reader not support seek", nil)
  39. ProxyNotSupportHttps = newTosClientError("proxy not support https", nil)
  40. ProxyUrlInvalid = newTosClientError("proxy url invalid", nil)
  41. NotificationConfigurationsInvalid = newTosClientError("Notification Configurations invalid", nil)
  42. InvalidCompleteAllPartsLength = newTosClientError("Should not specify both complete all and Parts", nil)
  43. InvalidPartsLength = newTosClientError("You must specify at least one part", nil)
  44. InvlidDeleteMultiObjectsLength = newTosClientError("You must specify at least one object", nil)
  45. )
  46. type TosError struct {
  47. Message string
  48. }
  49. func (e *TosError) Error() string {
  50. return e.Message
  51. }
  52. // for simplify code
  53. func newTosClientError(message string, cause error) *TosClientError {
  54. return &TosClientError{
  55. TosError: TosError{
  56. Message: message,
  57. },
  58. Cause: cause,
  59. }
  60. }
  61. type TosClientError struct {
  62. TosError
  63. Cause error
  64. }
  65. func (t *TosClientError) withCause(err error) error {
  66. t.Cause = err
  67. return t
  68. }
  69. // try to unmarshal server error from response
  70. func newTosServerError(res *Response) error {
  71. data, err := ioutil.ReadAll(io.LimitReader(res.Body, 64<<10)) // avoid too large
  72. if err != nil && len(data) <= 0 {
  73. return &TosServerError{
  74. TosError: TosError{"tos: server returned an empty body"},
  75. RequestInfo: res.RequestInfo(),
  76. }
  77. }
  78. se := Error{StatusCode: res.StatusCode}
  79. if err = json.Unmarshal(data, &se); err != nil {
  80. return &TosServerError{
  81. TosError: TosError{"tos: server returned an invalid body"},
  82. RequestInfo: res.RequestInfo(),
  83. }
  84. }
  85. return &TosServerError{
  86. TosError: TosError{se.Message},
  87. RequestInfo: res.RequestInfo(),
  88. Code: se.Code,
  89. HostID: se.HostID,
  90. Resource: se.Resource,
  91. }
  92. }
  93. // 服务端错误定义参考:https://www.volcengine.com/docs/6349/74874
  94. type TosServerError struct {
  95. TosError `json:"TosError"`
  96. RequestInfo `json:"RequestInfo"`
  97. Code string `json:"Code,omitempty"`
  98. HostID string `json:"HostID,omitempty"`
  99. Resource string `json:"Resource,omitempty"`
  100. }
  101. type Error struct {
  102. StatusCode int `json:"-"`
  103. Code string `json:"Code,omitempty"`
  104. Message string `json:"Message,omitempty"`
  105. RequestID string `json:"RequestId,omitempty"`
  106. HostID string `json:"HostId,omitempty"`
  107. Resource string `json:"Resource,omitempty"`
  108. }
  109. func (e *Error) Error() string {
  110. return fmt.Sprintf("tos: request error: StatusCode=%d, Code=%s, Message=%q, RequestID=%s, HostID=%s",
  111. e.StatusCode, e.Code, e.Message, e.RequestID, e.HostID)
  112. }
  113. // Code return error code saved in TosServerError
  114. func Code(err error) string {
  115. if er, ok := err.(*TosServerError); ok {
  116. return er.Code
  117. }
  118. return ""
  119. }
  120. // StatueCode return status code saved in TosServerError or UnexpectedStatusCodeError
  121. //
  122. // Deprecated: use StatusCode instead
  123. func StatueCode(err error) int {
  124. return StatusCode(err)
  125. }
  126. // StatusCode return status code saved in TosServerError or UnexpectedStatusCodeError
  127. func StatusCode(err error) int {
  128. if er, ok := err.(*TosServerError); ok {
  129. return er.StatusCode
  130. }
  131. if er, ok := err.(*UnexpectedStatusCodeError); ok {
  132. return er.StatusCode
  133. }
  134. return 0
  135. }
  136. func RequestID(err error) string {
  137. switch ev := err.(type) {
  138. case *TosServerError:
  139. return ev.RequestID
  140. case *UnexpectedStatusCodeError:
  141. return ev.RequestID
  142. case *ChecksumError:
  143. return ev.RequestID
  144. case *SerializeError:
  145. return ev.RequestID
  146. }
  147. return ""
  148. }
  149. type UnexpectedStatusCodeError struct {
  150. StatusCode int `json:"StatusCode,omitempty"`
  151. ExpectedCodes []int `json:"ExpectedCodes,omitempty"`
  152. RequestID string `json:"RequestId,omitempty"`
  153. expectedCodes [2]int
  154. responseMsg string
  155. err Error
  156. }
  157. func NewUnexpectedStatusCodeError(statusCode int, expectedCode int, expectedCodes ...int) *UnexpectedStatusCodeError {
  158. err := UnexpectedStatusCodeError{
  159. StatusCode: statusCode,
  160. }
  161. err.ExpectedCodes = err.expectedCodes[:0]
  162. err.ExpectedCodes = append(err.ExpectedCodes, expectedCode)
  163. err.ExpectedCodes = append(err.ExpectedCodes, expectedCodes...)
  164. return &err
  165. }
  166. func (us *UnexpectedStatusCodeError) WithRequestBody(res *Response) *UnexpectedStatusCodeError {
  167. data, err := ioutil.ReadAll(io.LimitReader(res.Body, 64<<10))
  168. if err != nil || len(data) <= 0 {
  169. return us
  170. }
  171. us.responseMsg = string(data)
  172. se := Error{StatusCode: res.StatusCode}
  173. err = json.Unmarshal(data, &se)
  174. if err != nil {
  175. return us
  176. }
  177. us.err = se
  178. return us
  179. }
  180. func (us *UnexpectedStatusCodeError) WithRequestID(requestID string) *UnexpectedStatusCodeError {
  181. us.RequestID = requestID
  182. return us
  183. }
  184. func (us *UnexpectedStatusCodeError) GoString() string {
  185. if us.responseMsg != "" {
  186. return fmt.Sprintf("tos.UnexpectedStatusCodeError{StatusCode:%d, ExpectedCodes:%v, RequestID:%s, ResponseErr:%s}",
  187. us.StatusCode, us.ExpectedCodes, us.RequestID, us.responseMsg)
  188. }
  189. return fmt.Sprintf("tos.UnexpectedStatusCodeError{StatusCode:%d, ExpectedCodes:%v, RequestID:%s}",
  190. us.StatusCode, us.ExpectedCodes, us.RequestID)
  191. }
  192. func (us *UnexpectedStatusCodeError) Error() string {
  193. if us.responseMsg != "" {
  194. return fmt.Sprintf("tos: unexpected status code error: StatusCode=%d, ExpectedCodes=%v, RequestID=%s, ResponseErr:%s",
  195. us.StatusCode, us.ExpectedCodes, us.RequestID, us.responseMsg)
  196. }
  197. return fmt.Sprintf("tos: unexpected status code error: StatusCode=%d, ExpectedCodes=%v, RequestID=%s",
  198. us.StatusCode, us.ExpectedCodes, us.RequestID)
  199. }
  200. type ChecksumError struct {
  201. RequestID string `json:"RequestId,omitempty"`
  202. ExpectedChecksum string `json:"ExpectedChecksum,omitempty"`
  203. ActualChecksum string `json:"ActualChecksum,omitempty"`
  204. }
  205. func (ce *ChecksumError) Error() string {
  206. return fmt.Sprintf("tos: checksum error: RequestID=%s, ExpectedChecksum=%s, ActualChecksum=%s",
  207. ce.RequestID, ce.ExpectedChecksum, ce.ActualChecksum)
  208. }
  209. type SerializeError struct {
  210. RequestID string `json:"RequestId,omitempty"`
  211. Message string `json:"Message,omitempty"`
  212. }
  213. func (se *SerializeError) Error() string {
  214. return fmt.Sprintf("tos: serialize error: RequestID=%s, Message=%q", se.RequestID, se.Message)
  215. }
  216. func checkError(res *Response, readBody bool, okCode int, okCodes ...int) error {
  217. if res.StatusCode == okCode {
  218. return nil
  219. }
  220. for _, code := range okCodes {
  221. if res.StatusCode == code {
  222. return nil
  223. }
  224. }
  225. defer res.Close()
  226. if readBody && res.StatusCode >= http.StatusBadRequest && res.Body != nil {
  227. return newTosServerError(res)
  228. // fall through
  229. }
  230. unexpected := NewUnexpectedStatusCodeError(res.StatusCode, okCode, okCodes...).
  231. WithRequestID(res.RequestInfo().RequestID)
  232. if readBody && res.Body != nil {
  233. unexpected = unexpected.WithRequestBody(res)
  234. }
  235. return &TosServerError{
  236. TosError: TosError{unexpected.Error()},
  237. RequestInfo: res.RequestInfo(),
  238. Code: unexpected.err.Code,
  239. HostID: unexpected.err.HostID,
  240. Resource: unexpected.err.Resource,
  241. }
  242. }
  243. // StatusCodeClassifier classifies Errors.
  244. // If the error is nil, it returns NoRetry;
  245. // if the error is TimeoutException or can be interpreted as TosServerError, and the StatusCode is 5xx or 429, it returns Retry;
  246. // otherwise, it returns NoRetry.
  247. type StatusCodeClassifier struct{}
  248. // Classify implements the classifier interface.
  249. func (classifier StatusCodeClassifier) Classify(err error) retryAction {
  250. if err == nil {
  251. return NoRetry
  252. }
  253. e, ok := err.(*TosServerError)
  254. if ok {
  255. if e.StatusCode >= 500 || e.StatusCode == 429 {
  256. return Retry
  257. }
  258. }
  259. cErr, ok := err.(*TosClientError)
  260. if ok {
  261. _, ok = cErr.Cause.(interface{ Timeout() bool })
  262. if ok {
  263. return Retry
  264. }
  265. }
  266. return NoRetry
  267. }
  268. // ServerErrorClassifier classify errors returned by POST method.
  269. // If the error is nil, it returns NoRetry;
  270. // if the error can be interpreted as TosServerError and its StatusCode is 5xx or 429, it returns Retry;
  271. // otherwise, it returns NoRetry.
  272. type ServerErrorClassifier struct{}
  273. // Classify implements the classifier interface.
  274. func (classifier ServerErrorClassifier) Classify(err error) retryAction {
  275. if err == nil {
  276. return NoRetry
  277. }
  278. e, ok := err.(*TosServerError)
  279. if ok {
  280. if e.StatusCode >= 500 || e.StatusCode == 429 {
  281. return Retry
  282. }
  283. }
  284. return NoRetry
  285. }
  286. type NoRetryClassifier struct{}
  287. // Classify implements the classifier interface.
  288. func (classifier NoRetryClassifier) Classify(_ error) retryAction {
  289. return NoRetry
  290. }