github.com/aavshr/aws-sdk-go@v1.41.3/example/aws/request/handleServiceErrorCodes/handleServiceErrorCodes.go (about)

     1  //go:build example
     2  // +build example
     3  
     4  package main
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	"github.com/aavshr/aws-sdk-go/aws"
    12  	"github.com/aavshr/aws-sdk-go/aws/awserr"
    13  	"github.com/aavshr/aws-sdk-go/aws/session"
    14  	"github.com/aavshr/aws-sdk-go/service/s3"
    15  )
    16  
    17  func exitErrorf(msg string, args ...interface{}) {
    18  	fmt.Fprintf(os.Stderr, msg+"\n", args...)
    19  	os.Exit(1)
    20  }
    21  
    22  // Will make a request to S3 for the contents of an object. If the request
    23  // was successful, and the object was found the object's path and size will be
    24  // printed to stdout.
    25  //
    26  // If the object's bucket or key does not exist a specific error message will
    27  // be printed to stderr for the error.
    28  //
    29  // Any other error will be printed as an unknown error.
    30  //
    31  // Usage: handleServiceErrorCodes <bucket> <key>
    32  func main() {
    33  	if len(os.Args) < 3 {
    34  		exitErrorf("Usage: %s <bucket> <key>", filepath.Base(os.Args[0]))
    35  	}
    36  	sess := session.Must(session.NewSession())
    37  
    38  	svc := s3.New(sess)
    39  	resp, err := svc.GetObject(&s3.GetObjectInput{
    40  		Bucket: aws.String(os.Args[1]),
    41  		Key:    aws.String(os.Args[2]),
    42  	})
    43  
    44  	if err != nil {
    45  		// Casting to the awserr.Error type will allow you to inspect the error
    46  		// code returned by the service in code. The error code can be used
    47  		// to switch on context specific functionality. In this case a context
    48  		// specific error message is printed to the user based on the bucket
    49  		// and key existing.
    50  		//
    51  		// For information on other S3 API error codes see:
    52  		// http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
    53  		if aerr, ok := err.(awserr.Error); ok {
    54  			switch aerr.Code() {
    55  			case s3.ErrCodeNoSuchBucket:
    56  				exitErrorf("bucket %s does not exist", os.Args[1])
    57  			case s3.ErrCodeNoSuchKey:
    58  				exitErrorf("object with key %s does not exist in bucket %s", os.Args[2], os.Args[1])
    59  			}
    60  		}
    61  		exitErrorf("unknown error occurred, %v", err)
    62  	}
    63  	defer resp.Body.Close()
    64  
    65  	fmt.Printf("s3://%s/%s exists. size: %d\n", os.Args[1], os.Args[2],
    66  		aws.Int64Value(resp.ContentLength))
    67  }