golang text/template renders panic into output text

69 Views Asked by At

I'm trying to render template, but it seems that there are some cases when error can be rendered directly into result text:

package main

import (
    "bytes"
    "fmt"
    "text/template"
    "time"
)

type MyDate struct {
    Time *time.Time
}

func (d *MyDate) String() string {
    // here will be a panic
    return d.Time.Format("15:04 02.01.2006")
}

type templateDto struct {
    Date *MyDate
}

func main() {
    s := `start
auto {{ .Date }}
finish`

    t := template.Must(template.New("test").Parse(s))
    buf := bytes.NewBuffer([]byte{})

    err := t.Execute(buf, &templateDto{
        Date: &MyDate{},
    })
    if err != nil {
        panic(err)
    }

    fmt.Printf("%s\n", buf.String())
}

https://go.dev/play/p/E0fP2b0rMHM

this code output is:

start
auto %!v(PANIC=String method: runtime error: invalid memory address or nil pointer dereference)
finish

the question is can i prevent rendering panics into the result, but get an error on execution instead?

0

There are 0 best solutions below