Formatted errors. New

I would like to implement a version errors.Newthat takes the same parameters as fmt.Sprintf. For this, I wrote the following function:

func NewError(format string, a ...interface{}) error {
    return errors.New(fmt.Sprintf(format, a))
}

However, ait becomes the only parameter of the array inside NewError(), thereby causing Sprintf()only one parameter to be filled in the format string. How can I make ainterpreted as a variable number of arguments?

+7
source share
2 answers

fmt.Errorfalready doing what you are trying to do. Looking at its source , you can see what went wrong:

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
        return errors.New(Sprintf(format, a...))
}

, ... a. :

...

[]T, ...T, .... .

s

s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)

Greeting, , s .

+15

@TimCooper :

package main

import (
    "fmt"
    "log"
)

func digitComparer(i, i2 int) error {
    if i != i2 {
        return fmt.Errorf("The digits a: '%d' and b: '%d' deviate.", i, i2)
    }
    return nil
}

func main() {
    err := digitComparer(22, 42)
    if err != nil {
        log.Fatal(err)
    }
}

, :

2009/11/10 23:00:00 The digits a: '22' and b: '42' deviate.
0

All Articles