golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.99k stars 17.67k forks source link

proposal: text/template: export error type for missingkey #57801

Open sding3 opened 1 year ago

sding3 commented 1 year ago

There is currently not an easy way to test for missing key error from text/template in the case that that the template was constructed with the missingkey=error option.

I propose adding a new error type in text/template testable via errors.As and the missing key can be recovered:

type MissingKeyError struct {
    Key string
}

func (e MissingKeyError) Error() string {
    return "no entry for key"
}

This would be added in a way that doesn't cause the existing error's string representation to change, allowing any users that might be checking for certain sub-string in the error strings to gracefully transition to the new way.


Edit: changed fmt.Errorf to errors.New Edit: took suggestion from @icholy to have the error be a struct type, allowing users to be able to recover the offending key.

seankhliao commented 1 year ago

cc @robpike

icholy commented 1 year ago

Perhaps something like:

type MissingKeyError struct {
    Key string
}

func (e MissingKeyError) Error() string {
    return "no entry for key"
}
sding3 commented 1 year ago

@icholy , great idea! I've updated the proposal.

sethvargo commented 1 year ago

It looks like this might already exist (except for write errors): https://github.com/golang/go/blob/master/src/text/template/exec.go#L118-L124

sding3 commented 1 year ago

It looks like this might already exist (except for write errors): https://github.com/golang/go/blob/master/src/text/template/exec.go#L118-L124

Can you show an example on programmatically detecting whether the cause for an ExecError is due to missing keys? I don't think that capability exists today unless you resort to sub-string checks against the error string, which isn't a reliable method.