graphql-go / handler

Golang HTTP.Handler for graphl-go
MIT License
445 stars 134 forks source link

Added Support for CustomErrorFormatter #46

Closed racerxdl closed 5 years ago

racerxdl commented 6 years ago

This is an add-on for https://github.com/graphql-go/graphql/pull/379 (it requires that to be merged to compile)

It basically adds a feature to be able to set a custom error formatter in case you have custom error objects returning in queries / mutation fields.

Example:

func CustomFormat(err error) gqlerrors.FormattedError {
    switch err := err.(type) {
    case *gqlerrors.Error:
        cf := CustomFormat(err.OriginalError)
        cf.Locations = err.Locations
        cf.Path = err.Path
        return cf
    case gqlerrors.ExtendedError:
        return gqlerrors.FormatError(err)
    case *QuantoError.ErrorObject:
        return err.ToFormattedError()
    default:
        return gqlerrors.FormatError(err)
    }
}

func GetGraphQLHandler(config graphql.SchemaConfig) *handler.Handler {
    schema, err := graphql.NewSchema(config)

    if err != nil {
        logger.Errorf("failed to create new schema, error: %v", err)
        return nil
    }

    h := handler.New(&handler.Config{
        Schema:   &schema,
        Pretty:   true,
        GraphiQL: true,
        CustomErrorFormatter: CustomFormat,
    })

    return h
}
limoli commented 6 years ago

Any news? @chris-ramon I think that this is an essential feature for a basic configuration of a response.

limoli commented 5 years ago

Some update? @chris-ramon

chris-ramon commented 5 years ago

Thanks a lot @racerxdl & @limoli for your great feedback, closing this one in favor of: https://github.com/graphql-go/handler/pull/58