talos
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5package client6
7import (8"errors"9
10"google.golang.org/grpc/codes"11"google.golang.org/grpc/status"12)
13
14// Status returns the status if it is a Status error, nil otherwise.
15func Status(err error) *status.Status {16type grpcStatus interface {17GRPCStatus() *status.Status18}19
20// Don't use FromError to avoid allocation of OK status.21var st grpcStatus22
23if errors.As(err, &st) {24return st.GRPCStatus()25}26
27return nil28}
29
30// StatusCode returns the Code of the error if it is a Status error, codes.OK if err
31// is nil, or codes.Unknown otherwise correctly unwrapping wrapped errors.
32//
33// StatusCode is mostly equivalent to grpc `status.Code` method, but it correctly unwraps wrapped errors
34// including `multierror.Error` used when parsing multi-node responses.
35func StatusCode(err error) codes.Code {36if err == nil {37return codes.OK38}39
40if st := Status(err); st != nil {41return st.Code()42}43
44return codes.Unknown45}
46