template_validation_recover.go 702 B

123456789101112131415161718192021222324252627282930
  1. // template_validation_recover.go
  2. package main
  3. import (
  4. "fmt"
  5. "log"
  6. "text/template"
  7. )
  8. func main() {
  9. tOk := template.New("ok")
  10. tErr := template.New("error_template")
  11. defer func() {
  12. if err := recover(); err != nil {
  13. log.Printf("run time panic: %v", err)
  14. }
  15. }()
  16. //a valid template, so no panic with Must:
  17. template.Must(tOk.Parse("/* and a comment */ some static text: {{ .Name }}"))
  18. fmt.Println("The first one parsed OK.")
  19. fmt.Println("The next one ought to fail.")
  20. template.Must(tErr.Parse(" some static text {{ .Name }"))
  21. }
  22. /* Output:
  23. The first one parsed OK.
  24. The next one ought to fail.
  25. 2011/10/27 10:56:27 run time panic: template: error_template:1: unexpected "}" in command
  26. */