-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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 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. – Volker Jun 15 '20 at 08:54
  • This is not exception (Golang does not have them, it's not Java). Your code just prints the error. – Andrejs Cainikovs Jun 15 '20 at 08:55
  • @Volker what I need to do is I need to check if this returned error is equal to `ResourceExistsException` – Escort Personal Adz Jun 15 '20 at 09: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. – Jonathan Hall Jun 15 '20 at 09:07

1 Answers1

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.

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118