Skip to content

proposal: text/template: allow callers to handle errors #52437

@bep

Description

@bep

Currently, if you do:

{{ $value := .Foo }}

And .Foo returns an error or panics, the template has no way to recover.

There are several good reasons why one might want to to handle this in the template, but mostly situations where the error situation is temporary (e.g. a remote server is failing) and some default content could be inserted.

The obvious solution would be to allow this:

{{ $value, $err := .Foo }}

Where $err would contain any error returned by or from a panic in .Foo. Any construct on the form {{ $value := .Foo }} would panic as before.

You could argue that .Foo could be rewritten to wrap any error, so you would get:

{{ $value:= .Foo }}
{{ if .Err }}
{{ else }}
   {{ .Value }}
{{ end }}

But that means that all existing APIs needs to be duplicated/wrapped – and the above does not resemble idiomatic Go code. It would also not handle runtime errors (e.g. invalid memory address or nil pointer dereference).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions