Error Handling in Templates


#1

From time to time I have data that will not work with some of the template functions.
Is there a way to just log it as a warning, not an error?

example:

{{ $date := dateFormat "Mon, 02 Jan 2006 15:04:05 MST" $data.date }}

with corrupt dates:

ERR: template: shortcodes/vulnerabilities.html:23:12: executing "shortcodes/vulnerabilities.html" at <dateFormat "Mon, 02 ...>: error calling dateFormat: Could not parse Date/Time format: Unable to parse date: 2017-02-06 21:29:29.160607648 +0000 UTC

is there a way of catching that error, and log some useful information?
I would rather have a page without the date, then nothing processed.


#2

Couldn’t you check the existing of a variable at runtime with the with keyword:

{{ with  $data.date }}
    {{ $date := dateFormat "Mon, 02 Jan 2006 15:04:05 MST" $data.date }}
    // do something with $date
{{ end }}

#3

the issue is not with non-existence, but with a parse error. in pure go I might do a sort of silent catch:

$date, err := dateFormat "Mon, 02 Jan 2006 15:04:05 MST" $data.date

but that does not work. I guess the dateFormat would need to support that. right? so my question is: could I wrap it in something which lets me do the same thing?

and this is just an example for the broader question if I can catch ERRORS during rendering, which I’m happy to ignore


#4

No, you can’t catch errors in a template.

The time parsing logic is from here. Several of the supported formats are from the Go time package.


#5

I also have the same question; but, in my case I am converting input to an integer:

{{ $number := int .Params.number }}

error calling int: unable to cast "24A" of type string to int`

I’d like to falback to a default value if it fails to convert. Perhaps I just need better data design.