7. 错误处理¶
1.通用的错误处理:
S3有一个通用的错误处理类:awserr.Error,通过了以下方法获取出错信息:
方法 | 说明 |
---|---|
Code | returns the classification code by which related errors are grouped. |
Message | returns a description of the error. |
OrigError | returns the original error of type error that is wrapped by the awserr.Error interface, such as a standard library error or a service error. |
awserr.Error的定义如下:
type Error interface {
// Satisfy the generic error interface.
error
// Returns the short phrase depicting the classification of the error.
Code() string
// Returns the error details message.
Message() string
// Returns the original error if one was set. Nil is returned if not set.
OrigErr() error
}
2.处理特殊的出错
svc := s3.New(sess)
resp, err := svc.GetObject(&s3.GetObjectInput{
Bucket: aws.String(os.Args[1]),
Key: aws.String(os.Args[2]),
})
if err != nil {
// http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case s3.ErrCodeNoSuchBucket:
exitErrorf("bucket %s does not exist", os.Args[1])
case s3.ErrCodeNoSuchKey:
exitErrorf("object with key %s does not exist in bucket %s", os.Args[2], os.Args[1])
}
}
}
Code | description |
---|---|
ErrCodeNoSuchBucket | 桶不存在 |
ErrCodeNoSuchKey | 对象不存在 |
ErrCodeBucketAlreadyExists | 桶已经被创建了,不属于您 |
ErrCodeBucketAlreadyOwnedByYou | 桶已经被创建了,且是您创建的 |
ErrCodeNoSuchUpload | 分块上传不存在 |
3.特殊的错误接口:MultiUploadFailure
接口定义如下:
type MultiUploadFailure interface {
awserr.Error
// Returns the upload id for the S3 multipart upload that failed.
UploadID() string
}