Source file src/errors/errors.go

     1  // Copyright 2011 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 errors implements functions to manipulate errors.
     6  //
     7  // The New function creates errors whose only content is a text message.
     8  //
     9  // The Unwrap, Is and As functions work on errors that may wrap other errors.
    10  // An error wraps another error if its type has the method
    11  //
    12  //	Unwrap() error
    13  //
    14  // If e.Unwrap() returns a non-nil error w, then we say that e wraps w.
    15  //
    16  // Unwrap unpacks wrapped errors. If its argument's type has an
    17  // Unwrap method, it calls the method once. Otherwise, it returns nil.
    18  //
    19  // A simple way to create wrapped errors is to call fmt.Errorf and apply the %w verb
    20  // to the error argument:
    21  //
    22  //	errors.Unwrap(fmt.Errorf("... %w ...", ..., err, ...))
    23  //
    24  // returns err.
    25  //
    26  // Is unwraps its first argument sequentially looking for an error that matches the
    27  // second. It reports whether it finds a match. It should be used in preference to
    28  // simple equality checks:
    29  //
    30  //	if errors.Is(err, fs.ErrExist)
    31  //
    32  // is preferable to
    33  //
    34  //	if err == fs.ErrExist
    35  //
    36  // because the former will succeed if err wraps fs.ErrExist.
    37  //
    38  // As unwraps its first argument sequentially looking for an error that can be
    39  // assigned to its second argument, which must be a pointer. If it succeeds, it
    40  // performs the assignment and returns true. Otherwise, it returns false. The form
    41  //
    42  //	var perr *fs.PathError
    43  //	if errors.As(err, &perr) {
    44  //		fmt.Println(perr.Path)
    45  //	}
    46  //
    47  // is preferable to
    48  //
    49  //	if perr, ok := err.(*fs.PathError); ok {
    50  //		fmt.Println(perr.Path)
    51  //	}
    52  //
    53  // because the former will succeed if err wraps an *fs.PathError.
    54  package errors
    55  
    56  // New returns an error that formats as the given text.
    57  // Each call to New returns a distinct error value even if the text is identical.
    58  func New(text string) error {
    59  	return &errorString{text}
    60  }
    61  
    62  // errorString is a trivial implementation of error.
    63  type errorString struct {
    64  	s string
    65  }
    66  
    67  func (e *errorString) Error() string {
    68  	return e.s
    69  }
    70  

View as plain text