github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/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 starlib
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  
    11  	"go.starlark.net/starlark"
    12  	"google.golang.org/genproto/googleapis/rpc/errdetails"
    13  	spb "google.golang.org/genproto/googleapis/rpc/status"
    14  	"google.golang.org/grpc/status"
    15  )
    16  
    17  type statusError interface{ GRPCStatus() *status.Status }
    18  
    19  func FprintStatus(w io.Writer, status *spb.Status) {
    20  	for _, detail := range status.Details {
    21  		m, err := detail.UnmarshalNew()
    22  		if err != nil {
    23  			fmt.Fprintf(w, "InternalError: %v\n", err)
    24  			continue
    25  		}
    26  		switch m := m.(type) {
    27  		case *errdetails.DebugInfo:
    28  			for _, se := range m.StackEntries {
    29  				fmt.Fprintln(w, se)
    30  			}
    31  		default:
    32  			fmt.Fprintf(w, "%v\n", m)
    33  		}
    34  	}
    35  	if len(status.Details) == 0 {
    36  		fmt.Fprintf(w, "Error: %v: %s\n", status.Code, status.Message)
    37  	}
    38  }
    39  
    40  func FprintErr(w io.Writer, err error) {
    41  	switch v := err.(type) {
    42  	case *starlark.EvalError:
    43  		fmt.Fprintln(w, v.Backtrace())
    44  	case statusError:
    45  		s := v.GRPCStatus()
    46  		p := s.Proto()
    47  		FprintStatus(w, p)
    48  	default:
    49  		fmt.Fprintln(w, err)
    50  	}
    51  }