Black Lives Matter. Support the Equal Justice Initiative.

Source file src/fmt/errors.go

Documentation: fmt

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fmt
     6  
     7  import "errors"
     8  
     9  // Errorf formats according to a format specifier and returns the string as a
    10  // value that satisfies error.
    11  //
    12  // If the format specifier includes a %w verb with an error operand,
    13  // the returned error will implement an Unwrap method returning the operand. It is
    14  // invalid to include more than one %w verb or to supply it with an operand
    15  // that does not implement the error interface. The %w verb is otherwise
    16  // a synonym for %v.
    17  func Errorf(format string, a ...interface{}) error {
    18  	p := newPrinter()
    19  	p.wrapErrs = true
    20  	p.doPrintf(format, a)
    21  	s := string(p.buf)
    22  	var err error
    23  	if p.wrappedErr == nil {
    24  		err = errors.New(s)
    25  	} else {
    26  		err = &wrapError{s, p.wrappedErr}
    27  	}
    28  	p.free()
    29  	return err
    30  }
    31  
    32  type wrapError struct {
    33  	msg string
    34  	err error
    35  }
    36  
    37  func (e *wrapError) Error() string {
    38  	return e.msg
    39  }
    40  
    41  func (e *wrapError) Unwrap() error {
    42  	return e.err
    43  }
    44  

View as plain text