github.com/searKing/golang/go@v1.2.117/error/cause/cause.go (about)

     1  // Copyright 2020 The searKing Author. 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 cause
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  )
    11  
    12  // WithError annotates cause error with a new error.
    13  // If cause is nil, WithError returns new error.
    14  // If err is nil, WithError returns nil.
    15  func WithError(cause error, err error) error {
    16  	if cause == nil {
    17  		return err
    18  	}
    19  	if err == nil {
    20  		return nil
    21  	}
    22  	return &withError{
    23  		cause: cause,
    24  		err:   err,
    25  	}
    26  }
    27  
    28  type withError struct {
    29  	cause error
    30  	err   error
    31  }
    32  
    33  func (w *withError) Error() string { return w.err.Error() + ": " + w.cause.Error() }
    34  func (w *withError) Cause() error  { return w.cause }
    35  
    36  func (w *withError) Format(s fmt.State, verb rune) {
    37  	switch verb {
    38  	case 'v':
    39  		if s.Flag('+') {
    40  			_, _ = fmt.Fprintf(s, "%+v\n", w.Cause())
    41  			_, _ = fmt.Fprintf(s, "%+v", w.err)
    42  			return
    43  		}
    44  		fallthrough
    45  	case 's', 'q':
    46  		_, _ = io.WriteString(s, w.Error())
    47  	}
    48  }