How do I access custom fields in an error?

748 Views Asked by At

Objective

Add a command to dropbox's CLI tool to get the shared link for the given path (file or folder).

The changes are here: github fork.

Background

The dropbox-go-sdk has a function that takes a path, and returns a new shared link, or returns an error containing the existing shared link.

I don't know how to use the error to extract the existing shared link.

Code

on github, and snippet here:

    dbx := sharing.New(config)
    res, err := dbx.CreateSharedLinkWithSettings(arg)
    if err != nil {
        switch e := err.(type) {
        case sharing.CreateSharedLinkWithSettingsAPIError:
            fmt.Printf("%v", e.EndpointError)
        default:
            return err
        }
    }

This prints the following:

&{{shared_link_already_exists} <nil> <nil>}found unknown shared link typeError: shared_link_already_exists/...

tracing: CreateSharedLinkWithSettings --> CreateSharedLinkWithSettingsAPIError --> CreateSharedLinkWithSettingsError --> SharedLinkAlreadyExistsMetadata --> IsSharedLinkMetadata

IsSharedLinkMetadata contains the Url that I'm looking for.

More Info

I struggle to understand how to deal with the error and extract the url from it.

  • The dbxcli has some code doing a similar operation, but again, not sure how it's working enough to apply it to the code I'm working on. Is it a Struct? Map? I don't know what this thing is called. There's some weird magic err.(type) stuff happening in the code. How do I access the data?
2

There are 2 best solutions below

0
On
dbx := sharing.New(config)
    res, err := dbx.CreateSharedLinkWithSettings(arg)
    if err != nil {
        switch e := err.(type) {
        case sharing.CreateSharedLinkWithSettingsAPIError:
            fmt.Printf("%v", e.EndpointError)
            // type cast to the specific error and access the field you want.
            settingsError := err.(sharing.CreateSharedLinkWithSettingsAPIError)
            fmt.Println(settingsError.EndpointError.SharedLinkAlreadyExists.Metadata.Url)
        default:
            return err
        }
    }
0
On

The question was answered in the comments by @jimb. The answer is you access the fields like any other golang data structure - nothing special.

The errors I got when trying to access the fields were because the fields were not there.

The problem with the code was dependency issues. The code depends on an older version of the go-sdk and I referenced the latest version.

This question serves as a good explanation for how real golang programmers handle errors in their code with examples. I wasn't able to find this online, so I won't close the question.