fatih / structtag

Parse and modify Go struct field tags
Other
633 stars 39 forks source link

Export error variables that are returned from exported methods; fix d… #16

Open slessard opened 3 years ago

slessard commented 3 years ago

Export error variables that are returned from exported methods fix documentation for Get method

fatih commented 3 years ago

Hi @slessard

If we expose these variables, they will become part of the library. I'm not sure I want to extend the API surface. How do you use it? I'm not sure exporting these variables is useful, but maybe I'm missing something. Thank you

slessard commented 3 years ago

Exporting the error variables would allow me to check the type of error in a manner that is friendly to recent versions of Go using the errors.Is function. Here's an example:

for ;; {
    tags, err := structtag.Parse(string(field.Tag))
    if errors.Is(err, structtag.ErrTagKeySyntax) ||
        errors.Is(err, structtag.ErrTagSyntax) ||
        errors.Is(err, structtag.ErrTagValueSyntax) {
        // These minor errors I can live with
        continue
    } else {
        // Houston, we have a problem.
        return err
    }
    authorizedRolesAsCSVString, err = tags.Get(rolesTagKey)
    if errors.Is(err, structtag.ErrTagNotExist) {
        // This kind of error I can handle. There just aren't any roles
        continue
    } else {
        // Getting tags failed in some unexpected way. Time to bail out
        return err
    }
    // Process tags here
}

Without exported error variables I don't know of a good way to test the error return. This forces me to make assumptions about the structtags functions and the errors they return.

BrianLeishman commented 2 years ago

I see the biggest pro argument as being able to tell whether or not a tag exists, just like @slessard has written an example for. It would be nice to skip an operation if the tag simply doesn't exist

zzjin commented 1 year ago

Any update here for 2 years wait?