github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/worker/errors.go (about)

     1  // Copyright 2022 Edward McFarlane. 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 worker
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  
    11  	"go.starlark.net/starlark"
    12  	"google.golang.org/genproto/googleapis/rpc/errdetails"
    13  	"google.golang.org/grpc/codes"
    14  	"google.golang.org/grpc/status"
    15  )
    16  
    17  // errorStatus creates a status from an error,
    18  // or its backtrace if it is a Starlark evaluation error.
    19  func errorStatus(err error) *status.Status {
    20  	if err == nil {
    21  		return nil
    22  	}
    23  	st, ok := status.FromError(err)
    24  	if !ok {
    25  		st = status.New(codes.InvalidArgument, err.Error())
    26  	}
    27  	if evalErr, ok := err.(*starlark.EvalError); ok {
    28  		// Describes additional debugging info.
    29  		di := &errdetails.DebugInfo{
    30  			StackEntries: strings.Split(evalErr.Backtrace(), "\n"),
    31  			Detail:       "<repl>",
    32  		}
    33  		st, err = st.WithDetails(di)
    34  		if err != nil {
    35  			// If this errored, it will always error
    36  			// here, so better panic so we can figure
    37  			// out why than have this silently passing.
    38  			panic(fmt.Sprintf("Unexpected error: %v", err))
    39  		}
    40  	}
    41  	return st
    42  
    43  }