Skip to content

Feature Request: Matchable errors for jwt.Token.Get #1425

@MB175

Description

@MB175

Feature Request: Matchable errors for jwt.Token.Get

Abstract

In lestrrat-go/jwx/jwt, methods like Token.Get(name, dst) return generic errors with messages such as:

return fmt.Errorf("field %q not found", name)
return fmt.Errorf("failed to assign value to dst: %w", err)

This makes it hard for users to differentiate between a missing claim, a type conversion failure, or other errors. The proposal is to introduce matchable errors (sentinels or typed errors) for clearer, idiomatic handling.

Proposed solution

Introduce exported sentinel errors:

var (
    ErrFieldNotFound = errors.New("field not found")
    ErrAssignFailed  = errors.New("failed to assign value")
)

Update Get to wrap them:

if t.claims[name] == nil {
    return fmt.Errorf("%w: %q", ErrFieldNotFound, name)
}
if err := blackmagic.AssignIfCompatible(dst, t.claims[name]); err != nil {
    return fmt.Errorf("%w: %w", ErrAssignFailed, err)
}

Alternatively, use typed errors:

type FieldNotFoundError struct {
    Field string
}
func (e FieldNotFoundError) Error() string {
    return fmt.Sprintf("field %q not found", e.Field)
}

Example usage:

var fnf jwt.FieldNotFoundError
if errors.As(err, &fnf) {
    log.Printf("missing claim: %s", fnf.Field)
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions