-
Notifications
You must be signed in to change notification settings - Fork 494
Closed
Description
I noticed #49 supports custom errors. However, there is no documentation for how to use them.
I want to add a few extra fields to my errors.
Here's what I've done:
package main
import (
"log"
"net/http"
"encoding/json"
"fmt"
"github.com/neelance/graphql-go"
"github.com/neelance/graphql-go/errors"
)
type CustomErr struct {
errors.QueryError
Code string `json:"code"`
AnotherField string `json:"anotherField"`
}
var Schema = `
schema {
query: Query
mutation: Mutation
}
type Query {
}
type Mutation {
createReview(review: String!): Review
}
type Review {
stars: Int!
}
`
type Resolver struct{}
func (r *Resolver) CreateReview(args *struct {
Review string
}) (*reviewResolver, error) {
return nil, &CustomErr{
Code: "TEST_CODE",
AnotherField: "TESTTEST",
QueryError: errors.QueryError{
Message: "test_error",
},
}
//return &reviewResolver{5}, nil
}
type reviewResolver struct {
stars int32
}
func (r *reviewResolver) Stars() int32 {
return r.stars
}
type Handler struct {
Schema *graphql.Schema
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println(string(responseJSON))
w.Write(responseJSON)
}
func main() {
s, err := graphql.ParseSchema(Schema, &Resolver{})
if err != nil {
panic(err)
}
http.Handle("/", &Handler{Schema: s})
log.Fatal(http.ListenAndServe(":13371", nil))
}
This is the response I get (custom fields missing):
{
"data": {
"createReview": null
},
"errors": [
{
"message": "graphql: test_error"
}
]
}
Metadata
Metadata
Assignees
Labels
No labels