File size: 1,255 Bytes
fea99b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package errorsx

import (
	"errors"
	"reflect"
	"slices"

	api "github.com/openmeterio/openmeter/api"
	apiv3 "github.com/openmeterio/openmeter/api/v3"
)

var apiErrorPackages = []string{
	reflect.TypeOf(api.InvalidParamFormatError{}).PkgPath(),
	reflect.TypeOf(apiv3.InvalidParamFormatError{}).PkgPath(),
}

func isAPIError(err error) bool {
	// Package matching is the most maintainable way to identify generated API errors.
	// The codegen output does not provide a common base error or helper for them.
	return isErrorFromPackages(err, apiErrorPackages)
}

func isErrorFromPackages(err error, packagePaths []string) bool {
	if err == nil {
		return false
	}

	t := reflect.TypeOf(err)
	for t.Kind() == reflect.Pointer {
		t = t.Elem()
	}

	if slices.Contains(packagePaths, t.PkgPath()) {
		return true
	}

	return isUnwrappedErrorFromPackages(err, packagePaths)
}

func isUnwrappedErrorFromPackages(err error, packagePaths []string) bool {
	unwrapped := errors.Unwrap(err)
	if unwrapped != nil {
		return isErrorFromPackages(unwrapped, packagePaths)
	}

	if unwrapper, ok := err.(interface{ Unwrap() []error }); ok {
		for _, err := range unwrapper.Unwrap() {
			if isErrorFromPackages(err, packagePaths) {
				return true
			}
		}
	}

	return false
}