~bigbes/core-go

ref: 038a9eb03a3043e4ee418a8b24a8769c37c82006 core-go/errors/errors.go -rw-r--r-- 1.2 KiB
038a9eb0 — Drew DeVault auth: add error code on unauthorized request response 10 months ago
                                                                                
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
package errors

import (
	"fmt"

	"github.com/vektah/gqlparser/v2/gqlerror"
)

type ErrorCode string

// Creates a new GraphQL error with a standard error code.
func New(code ErrorCode, message string) *gqlerror.Error {
	return &gqlerror.Error{
		Message:    message,
		Extensions: map[string]any{"code": code},
	}
}

// Creates a new GraphQL error with a standard error code.
func Errorf(code ErrorCode, format string, a ...any) *gqlerror.Error {
	return &gqlerror.Error{
		Message:    fmt.Sprintf(format, a...),
		Extensions: map[string]any{"code": code},
	}
}

// Sets the field name that caused the error
func Field(err *gqlerror.Error, field string) *gqlerror.Error {
	err.Extensions["field"] = field
	return err
}

// Error codes as string constants
var (
	AccessDenied ErrorCode = "ERR_ACCESS_DENIED"
	NotFound     ErrorCode = "ERR_NOT_FOUND"
	Unsupported  ErrorCode = "ERR_UNSUPPORTED"
	Unauthorized ErrorCode = "ERR_UNAUTHORIZED"
)

// Error codes as Go errors
var (
	ErrAccessDenied = New(AccessDenied, "Access denied")
	ErrNotFound     = New(NotFound, "Resource not found")
	ErrUnsupported  = New(Unsupported, "Not supported")
	ErrUnauthorized = New(Unauthorized, "Unauthorized")
)