From 8927c49bddd6aae4a4c4120141eccb5f973bf560 Mon Sep 17 00:00:00 2001 From: jsvisa Date: Wed, 25 Oct 2023 09:48:08 +0800 Subject: [PATCH] graphql: customize error response Signed-off-by: jsvisa --- graphql/errors.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++ graphql/graphql.go | 5 ----- 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 graphql/errors.go diff --git a/graphql/errors.go b/graphql/errors.go new file mode 100644 index 0000000000..9e094a1b9a --- /dev/null +++ b/graphql/errors.go @@ -0,0 +1,54 @@ +// Copyright 2023 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +// Package graphql provides a GraphQL interface to Ethereum node data. +package graphql + +import ( + "errors" + "fmt" +) + +var ( + errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash") + errInvalidBlockRange = errors.New("invalid from and to block combination: from > to") +) + +type graphQLError struct { + Code string `json:"code"` + Message string `json:"message"` +} + +// Error implements the github.com/graph-gophers/graphql-go.ResolverError interface. +func (e *graphQLError) Error() string { + return fmt.Sprintf("error [%s]: %s", e.Code, e.Message) +} + +// Extensions implements the github.com/graph-gophers/graphql-go.ResolverError interface. +func (e *graphQLError) Extensions() map[string]interface{} { + return map[string]interface{}{ + "code": e.Code, + "message": e.Message, + } +} + +// asGraphQLError wraps an error into graphQLError +func asGraphQLError(err error) error { + if err == nil { + return nil + } + return &graphQLError{Code: "-32602", Message: err.Error()} +} diff --git a/graphql/graphql.go b/graphql/graphql.go index 93313d743a..e97f34a463 100644 --- a/graphql/graphql.go +++ b/graphql/graphql.go @@ -40,11 +40,6 @@ import ( "github.com/ethereum/go-ethereum/rpc" ) -var ( - errBlockInvariant = errors.New("block objects must be instantiated with at least one of num or hash") - errInvalidBlockRange = errors.New("invalid from and to block combination: from > to") -) - type Long int64 // ImplementsGraphQLType returns true if Long implements the provided GraphQL type.