This topic describes how to handle errors for the Go SDK.
Client-side errors
If a call made by the Go SDK fails, it returns an error interface. This interface is defined as follows:
type error interface {
Error() string
}Other errors inherit from this interface. For example, the error that is returned when an HTTP request fails is defined as follows:
//net.Error
type Error interface {
error
Timeout() bool // Is the error a timeout
Temporary() bool // Is the error temporary
}Server-side errors
If a request made by the OSS Go SDK fails, an error is returned. For issues such as HTTP request or I/O errors, a custom Go error is returned. If an error occurs on the OSS server, the following error is returned. This error implements the Error interface.
type ServiceError struct {
Code string // The error code returned by OSS.
Message string // The detailed error message from OSS.
RequestId string // The universally unique identifier (UUID) that uniquely identifies the request.
HostId string // The ID of the OSS cluster that is accessed.
StatusCode int // The HTTP status code.
}If the HTTP status code returned by OSS does not match the expected code, the following error is returned. This error also implements the Error interface.
type UnexpectedStatusCodeError struct {
allowed []int // The expected HTTP status codes from OSS.
got int // The actual HTTP status code returned by OSS.
}Error handling example
The following code shows how to handle errors:
package main
import (
"fmt"
"os"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// The error handling function.
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
/// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the bucket. For example, for the China (Hangzhou) region, use https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
// Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, use cn-hangzhou. For other regions, use the actual region ID.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
HandleError(err)
}
// Specify the bucket name, for example, examplebucket.
bucketName := "examplebucket"
// Specify the object name, for example, exampleobject.txt.
objectName := "exampleobject.txt"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Upload a string.
err = bucket.PutObject(objectName, strings.NewReader("Hello OSS"))
if err != nil {
HandleError(err)
}
}
OSS error codes
The following table lists the OSS error codes.
Error code | Description | HTTP status code |
AccessDenied | Access denied. | 403 |
BucketAlreadyExists | The bucket already exists. | 409 |
BucketNotEmpty | The bucket is not empty. | 409 |
EntityTooLarge | The entity is too large. | 400 |
EntityTooSmall | The entity is too small. | 400 |
FileGroupTooLarge | The file group is too large. | 400 |
InvalidLinkName | The object link has the same name as the object to which it points. | 400 |
LinkPartNotExist | The object to which the object link points does not exist. | 400 |
ObjectLinkTooLarge | The number of objects in the object link is too large. | 400 |
FieldItemTooLong | The form field in the POST request is too large. | 400 |
FilePartInterity | The file part has changed. | 400 |
FilePartNotExist | The file part does not exist. | 400 |
FilePartStale | The file part is stale. | 400 |
IncorrectNumberOfFilesInPOSTRequest | The number of files in the POST request is invalid. | 400 |
InvalidArgument | The parameter format is invalid. | 400 |
InvalidAccessKeyId | The AccessKey ID does not exist. | 403 |
InvalidBucketName | The bucket name is invalid. | 400 |
InvalidDigest | The digest is invalid. | 400 |
InvalidEncryptionAlgorithmError | The specified encryption algorithm for entropy encoding is invalid. | 400 |
InvalidObjectName | The object name is invalid. | 400 |
InvalidPart | The part is invalid. | 400 |
InvalidPartOrder | The part order is invalid. | 400 |
InvalidPolicyDocument | The policy document is invalid. | 400 |
InvalidTargetBucketForLogging | The target bucket for the logging operation is invalid. | 400 |
InternalError | An internal error occurred in OSS. | 500 |
MalformedXML | The XML format is invalid. | 400 |
MalformedPOSTRequest | The body format of the POST request is invalid. | 400 |
MaxPOSTPreDataLengthExceededError | The body of the POST request, excluding the uploaded file content, is too large. | 400 |
MethodNotAllowed | The method is not supported. | 405 |
MissingArgument | A parameter is missing. | 411 |
MissingContentLength | The content length is missing. | 411 |
NoSuchBucket | The bucket does not exist. | 404 |
NoSuchKey | The file does not exist. | 404 |
NoSuchUpload | The multipart upload ID does not exist. | 404 |
NotImplemented | The method cannot be processed. | 501 |
PreconditionFailed | A pre-processing error occurred. | 412 |
RequestTimeTooSkewed | The time difference between the client and the OSS server is more than 15 minutes. | 403 |
RequestTimeout | The request timed out. | 400 |
RequestIsNotMultiPartContent | The Content-Type of the POST request is invalid. | 400 |
SignatureDoesNotMatch | The signature is invalid. | 403 |
TooManyBuckets | The number of buckets has exceeded the limit. | 400 |
InvalidEncryptionAlgorithmError | The specified entropy encoding encryption algorithm is invalid. | 400 |
In the preceding table, Error code corresponds to OssServiceError.Code, and HTTP status code corresponds to OssServiceError.StatusCode.