github.com/blend/go-sdk@v1.20220411.3/ex/is.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package ex
     9  
    10  import "errors"
    11  
    12  // Is is a helper function that returns if an error is an ex.
    13  //
    14  // It will handle if the err is an exception, a multi-error or a regular error.
    15  // "Isness" is evaluated by if the class of the exception matches the class of the cause
    16  func Is(err interface{}, cause error) bool {
    17  	if err == nil || cause == nil {
    18  		return false
    19  	}
    20  	if typed := As(err); typed != nil {
    21  		if typed.Class == nil {
    22  			return false
    23  		}
    24  		if causeTyped := As(cause); causeTyped != nil {
    25  			if causeTyped.Class == nil {
    26  				return false
    27  			}
    28  			return typed.Class == causeTyped.Class
    29  		}
    30  		return (typed.Class == cause) || (typed.Class.Error() == cause.Error()) || errors.Is(typed.Class, cause)
    31  	}
    32  	if typed, ok := err.(ClassProvider); ok {
    33  		return typed.Class() == cause || (typed.Class().Error() == cause.Error()) || errors.Is(typed.Class(), cause)
    34  	}
    35  
    36  	// handle the case of multi-exceptions
    37  	if multiTyped, ok := err.(Multi); ok {
    38  		for _, multiErr := range multiTyped {
    39  			if Is(multiErr, cause) {
    40  				return true
    41  			}
    42  		}
    43  		return false
    44  	}
    45  
    46  	// handle regular errors
    47  	if typed, ok := err.(error); ok && typed != nil {
    48  		return (err == cause) || (typed.Error() == cause.Error()) || errors.Is(typed, cause)
    49  	}
    50  	// handle ???
    51  	return err == cause
    52  }