CloudyKit / jet

Jet template engine
Apache License 2.0
1.26k stars 106 forks source link

How to handle error in custom functions? #174

Closed razonyang closed 4 years ago

razonyang commented 4 years ago

Hi, I follow the wiki to create a custom function:

set.AddGlobalFunc("foo", func(args jet.Arguments) reflect.Value {
    v, err := doStaff()
    if err != nil {
         // handle error
    }

    return reflect.ValueOf(v) 
})

What is the proper way to handle error? Should I use panic?

Does Jet provide a way to handle function call errors globally, so that we can define function like:

func(args jet.Arguments) (reflect.Value, error) {
    v, err := doStaff()
    if err != nil {
         return reflect.Value{}, err
    }

    return reflect.ValueOf(v), nil
}
sauerbraten commented 4 years ago

Jet doesn't support your function returning an error.

Whether you should use panic or not depends on what you want to happen: if the error means you can't continue rendering the template, use panic. Jet will recover from it and show you where the error occured, instead of rendering the template. If it's not a fatal error, you can log that something went wrong and then return a default (valid) value that will allow Jet to continue rendering your template.

Does that answer your question?

razonyang commented 4 years ago

Got it, thanks!