File: error.go

package info (click to toggle)
golang-github-einride-aip-go 0.80.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,108 kB
  • sloc: makefile: 147
file content (73 lines) | stat: -rw-r--r-- 2,076 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package validation

import (
	"fmt"
	"strings"

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// Error represents a message validation error.
type Error struct {
	fieldViolations []*errdetails.BadRequest_FieldViolation
	grpcStatus      *status.Status
	str             string
}

// NewError creates a new validation error from the provided field violations.
func NewError(fieldViolations []*errdetails.BadRequest_FieldViolation) error {
	if len(fieldViolations) == 0 {
		panic("validation.NewError: must provide at least one field violation")
	}
	return &Error{
		fieldViolations: fieldViolations,
	}
}

// GRPCStatus converts the validation error to a gRPC status with code INVALID_ARGUMENT.
func (e *Error) GRPCStatus() *status.Status {
	if e.grpcStatus == nil {
		var fields strings.Builder
		for i, fieldViolation := range e.fieldViolations {
			_, _ = fields.WriteString(fieldViolation.GetField())
			if i < len(e.fieldViolations)-1 {
				_, _ = fields.WriteString(", ")
			}
		}
		withoutDetails := status.Newf(codes.InvalidArgument, "invalid fields: %s", fields.String())
		if withDetails, err := withoutDetails.WithDetails(&errdetails.BadRequest{
			FieldViolations: e.fieldViolations,
		}); err != nil {
			e.grpcStatus = withoutDetails
		} else {
			e.grpcStatus = withDetails
		}
	}
	return e.grpcStatus
}

// Error implements the error interface.
func (e *Error) Error() string {
	if e.str == "" {
		if len(e.fieldViolations) == 1 {
			e.str = fmt.Sprintf(
				"field violation on %s: %s",
				e.fieldViolations[0].GetField(),
				e.fieldViolations[0].GetDescription(),
			)
		} else {
			var result strings.Builder
			_, _ = result.WriteString("field violation on multiple fields:\n")
			for i, fieldViolation := range e.fieldViolations {
				_, _ = result.WriteString(fmt.Sprintf(" | %s: %s", fieldViolation.GetField(), fieldViolation.GetDescription()))
				if i < len(e.fieldViolations)-1 {
					_ = result.WriteByte('\n')
				}
			}
			e.str = result.String()
		}
	}
	return e.str
}