Upgrade to Pro — share decks privately, control downloads, hide ads and more …

GraphQL Better Errors

ogom
October 13, 2019

GraphQL Better Errors

ogom

October 13, 2019
Tweet

More Decks by ogom

Other Decks in Programming

Transcript

  1. Prerelease Working Draft Sat, Oct 5, 2019 Latest Release June

    2018 Sun, Jun 10, 2018 Release Notes October 2016 Mon, Oct 31, 2016 Release Notes April 2016 Thu, Apr 7, 2016 Release Notes October 2015 Thu, Oct 1, 2015 Release Notes July 2015 Thu, Jul 2, 2015 Release Notes GraphQL
  2. 3FTQPOTF&SSPST Example No 189 { "errors": [ { "message": "Name

    for character with ID 1002 could not be fetched.", "locations": [ { "line": 6, "column": 7 } ], "path": [ "hero", "heroFriends", 1, "name" ], "extensions": { "code": "CAN_NOT_FETCH_BY_ID", "timestamp": "Fri Feb 9 14:33:09 UTC 2018" } } ] }
  3. "VUIFOUJDBUJPO&SSPS const { ApolloServer, gql, AuthenticationError } = require("apollo-server"); const

    typeDefs = gql` type Query { authenticationError: String } `; const resolvers = { Query: { authenticationError: (parent, args, context) => { throw new AuthenticationError("must authenticate"); } } };
  4. \ FSSPST< \ NFTTBHFNVTUBVUIFOUJDBUF  MPDBUJPOT< \ MJOF  DPMVNO

    ^ >  QBUI< BVUIFOUJDBUJPO&SSPS >  FYUFOTJPOT\ DPEF6/"65)&/5*$"5&%  ^ ^ >  EBUB\ BVUIFOUJDBUJPO&SSPSOVMM ^ ^
  5. HSBQI2-&SSPST import { ApolloProvider, useQuery } from “@apollo/react-hooks"; function Element()

    { const { loading, error, data } = useQuery(gql` { authenticationError } `); if (loading) return <p>Loading...</p>; if (error) { return error.graphQLErrors.map(({ message, extensions }, i) => ( <div key={i}>{message}: {extensions.code}</div> )) } }
  6. (SBQI2-&YFDVUJPO&SSPS class MySchema < GraphQL::Schema use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST use

    GraphQL::Execution::Errors rescue_from(ActiveRecord::RecordNotFound) do |err, obj, args, ctx, field| GraphQL::ExecutionError.new( err.message, extensions: {code: ‘RecordNotFound'} ) end end
  7. { "data": null, "errors": [ { "message": "Couldn't find User",

    "locations": [ { "line": 2, "column": 3 } ], "path": [ "user" ], "extensions": { "code": "RecordNotFound" } } ] }
  8. (SBQI2-$PFSDJPO&SSPS module Types class EmailAddress < Types::BaseScalar def self.coerce_input(value, _context)

    unless URI::MailTo::EMAIL_REGEXP.match(value) raise GraphQL::CoercionError.new( "#{value} is not a valid email address", extensions: { code: “Invalid_Email" } ) end value end end end
  9. { "errors": [ { "message": "example.com is not a valid

    email address", "locations": [ { "line": 2, "column": 3 } ], "path": [ "query", "user", "email" ], "extensions": { "code": "Invalid_Email", "typeName": "CoercionError" } } ] }