-1

I need to know how to explicitly catch a certain error (exception).

Here is my code:

package main

import (
    "bufio"
    "bytes"
    "compress/gzip"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path"
    "strings"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/secretsmanager"
)

func main() {
svc := secretsmanager.New(session.New())

result, err := svc.CreateSecret(inputCert)
            if err != nil {
                fmt.Println(err) //this gives the error "ResourceExistsException"
            }
            fmt.Println(result)
}

The exception I am getting is ResourceExistsException. The whole output is:

ResourceExistsException: The operation failed because the secret test/nse/test.crt already exists.

What I want to do this, I want to explicity get this exception as there can be other exceptions too (other than ResourceExistsException)

How can I do this?

4
  • Go (which is the proper name if the language) has no exceptions. (It has panics, but your case here is not a panic but a returned error). What exactly do you mean when you say "I want to explicity get this exception"? There is no exception and you can do with the error returned whatever you want. Commented Jun 15, 2020 at 8:54
  • This is not exception (Golang does not have them, it's not Java). Your code just prints the error. Commented Jun 15, 2020 at 8:55
  • @Volker what I need to do is I need to check if this returned error is equal to ResourceExistsException Commented Jun 15, 2020 at 9:03
  • 1
    Go has no exceptions, and can't "catch" anything. But if what you mean is "How can I determine if an error value represents a specific error?" then see the duplicate link. If you mean something else, you must clarify. Commented Jun 15, 2020 at 9:07

1 Answer 1

1

To handle specific errors from the aws API, you can check the type of the error returned.

result, err := svc.CreateSecret(inputCert)
if err != nil {
    switch terr := err.(type) {
    case *secretsmanager.ResourceNotFoundException:
        // use "terr" which will be a value of the *ResourceNotFoundException type.
    default:
        fmt.Println("unhandled error of type %T: %s", err, err)
    }
}

I've used a switch here, because probably you want to check a few different error types, but you can use a simple type assertion if you just have one error type.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me for sdk-v2 github.com/aws/aws-sdk-go-v2/issues/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.