github.com/tilt-dev/wat@v0.0.2-0.20180626175338-9349b638e250/errors/errors.go (about)

     1  // Go's error library is very minimalist.
     2  //
     3  // Go doesn't express an opinionated way to do common error operations, like
     4  // error codes and error causes (in contrast to Java's more full-featured
     5  // Throwable hierarchy).
     6  //
     7  // Sadly, this means that every third-party Go library implements their
     8  // own way of doing these things (e.g., context.Canceled vs grpc/codes.Canceled).
     9  //
    10  // The purpose of this package is to normalize error-handling across these
    11  // third-party libraries.
    12  
    13  package errors
    14  
    15  import (
    16  	"context"
    17  	"fmt"
    18  
    19  	"google.golang.org/grpc"
    20  	"google.golang.org/grpc/codes"
    21  	"google.golang.org/grpc/status"
    22  )
    23  
    24  func IsCanceled(err error) bool {
    25  	if err == context.Canceled {
    26  		return true
    27  	}
    28  	code := grpc.Code(err)
    29  	if code == codes.Canceled {
    30  		return true
    31  	}
    32  	return false
    33  }
    34  
    35  func IsDeadlineExceeded(err error) bool {
    36  	if err == context.DeadlineExceeded {
    37  		return true
    38  	}
    39  	code := grpc.Code(err)
    40  	if code == codes.DeadlineExceeded {
    41  		return true
    42  	}
    43  	return false
    44  }
    45  
    46  // Propagatef follows the convention that any function ending in 'f' takes
    47  // a format string. We also tell go vet about this function so that it can
    48  // check the format string validity.
    49  func Propagatef(err error, msg string, args ...interface{}) error {
    50  	st, ok := status.FromError(err)
    51  	if ok {
    52  		return grpc.Errorf(st.Code(), "%s: %v", fmt.Errorf(msg, args...), st.Message())
    53  	}
    54  	if IsDeadlineExceeded(err) {
    55  		return grpc.Errorf(codes.DeadlineExceeded, "%s: %v", fmt.Errorf(msg, args...), err)
    56  	}
    57  	if IsCanceled(err) {
    58  		return grpc.Errorf(codes.Canceled, "%s: %v", fmt.Errorf(msg, args...), err)
    59  	}
    60  	return fmt.Errorf("%s: %v", fmt.Errorf(msg, args...), err)
    61  }