1
0
mirror of https://github.com/golang/go synced 2024-11-24 17:30:18 -07:00

template: format errors

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/5340043
This commit is contained in:
Russ Cox 2011-11-04 07:33:55 -04:00
parent cb2040b2ab
commit e73680aec0
3 changed files with 7 additions and 3 deletions

View File

@ -445,7 +445,7 @@ func methodByName(receiver reflect.Value, name string) (reflect.Value, bool) {
} }
var ( var (
osErrorType = reflect.TypeOf((*error)(nil)).Elem() errorType = reflect.TypeOf((*error)(nil)).Elem()
fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
) )
@ -659,7 +659,7 @@ func (s *state) printValue(n parse.Node, v reflect.Value) {
return return
} }
if !v.Type().Implements(fmtStringerType) { if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
if v.CanAddr() && reflect.PtrTo(v.Type()).Implements(fmtStringerType) { if v.CanAddr() && reflect.PtrTo(v.Type()).Implements(fmtStringerType) {
v = v.Addr() v = v.Addr()
} else { } else {

View File

@ -6,6 +6,7 @@ package template
import ( import (
"bytes" "bytes"
"errors"
"flag" "flag"
"fmt" "fmt"
"os" "os"
@ -52,6 +53,7 @@ type T struct {
NonEmptyInterface I NonEmptyInterface I
// Stringer. // Stringer.
Str fmt.Stringer Str fmt.Stringer
Err error
// Pointers // Pointers
PI *int PI *int
PSI *[]int PSI *[]int
@ -99,6 +101,7 @@ var tVal = &T{
Empty4: &U{"UinEmpty"}, Empty4: &U{"UinEmpty"},
NonEmptyInterface: new(T), NonEmptyInterface: new(T),
Str: bytes.NewBuffer([]byte("foozle")), Str: bytes.NewBuffer([]byte("foozle")),
Err: errors.New("erroozle"),
PI: newInt(23), PI: newInt(23),
PSI: newIntSlice(21, 22, 23), PSI: newIntSlice(21, 22, 23),
Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X
@ -416,6 +419,7 @@ var execTests = []execTest{
{"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true}, {"bug4", "{{if .Empty0}}non-nil{{else}}nil{{end}}", "nil", tVal, true},
// Stringer. // Stringer.
{"bug5", "{{.Str}}", "foozle", tVal, true}, {"bug5", "{{.Str}}", "foozle", tVal, true},
{"bug5a", "{{.Err}}", "erroozle", tVal, true},
// Args need to be indirected and dereferenced sometimes. // Args need to be indirected and dereferenced sometimes.
{"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true}, {"bug6a", "{{vfunc .V0 .V1}}", "vfunc", tVal, true},
{"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true}, {"bug6b", "{{vfunc .V0 .V0}}", "vfunc", tVal, true},

View File

@ -72,7 +72,7 @@ func goodFunc(typ reflect.Type) bool {
switch { switch {
case typ.NumOut() == 1: case typ.NumOut() == 1:
return true return true
case typ.NumOut() == 2 && typ.Out(1) == osErrorType: case typ.NumOut() == 2 && typ.Out(1) == errorType:
return true return true
} }
return false return false