Այժմ դուք կարող եք վերադարձնել մաքսային սխալները statusCode-ով GraphQL-ում մի քանի տող կոդով: Դուք կարող եք լռելյայնորեն վերադարձնել HTTP սխալները, բայց նաև կարող եք ստեղծել հատուկ սխալներ:

Ինչպես դա անել:

  • Ներմուծեք գրադարանը const FormatError = require('easygraphql-format-error)
  • Նախաձեռնեք const formatError = new FormatError(), դուք կարող եք փոխանցել սովորական սխալներ const formatError = new FormatError([{name: INVALID_EMAIL, message: 'The email is not valid', statusCode: 400 }]) զանգվածի ներսում
  • Փոխանցեք errorName-ը լուծողներին const errorName = formatError.errorName համատեքստում
  • Եթե ​​կա սխալ throw new Error(errorName.UNAUTHORIZED)

Օրինակ:

GraphQL սխեման.

type Query {
  userInformation(isLoggedIn: Boolean!): String!
  findUserByEmail(email: String!): String!
}

App.js

'use strict' 
const express = require('express')
const { buildSchema } = require('graphql')
const graphqlHTTP = require('express-graphql')
const bodyParser = require('body-parser')
const FormatError = require('easygraphql-format-error') 
const fs = require('fs')
const path = require('path') 
const root = require('./schema/resolvers') 
const app = express() 
app.set('port', process.env.PORT || 7000)
app.use(bodyParser.json({limit: '10mb'}))
app.use(bodyParser.urlencoded({ extended: true })) 
const formatError = new FormatError([
  {  
    name: 'INVALID_EMAIL',  
    message: 'The email is not valid',  
    statusCode: 400
  }
])
const errorName = formatError.errorName 
const schemaCode = fs.readFileSync(path.join(__dirname, 'schema', 'schema.gql'), 'utf8')
const schema = buildSchema(schemaCode) 
app.use('/', (req, res) => {  
  graphqlHTTP({    
    schema,    
    rootValue: root,    
    graphiql: true,    
    context: { errorName },    
    formatError: (err) => {      
      return formatError.getError(err)    
    }  
  })(req, res)
}) 
const server = app.listen(app.get('port'), () => {     
  console.log(`Server running -> PORT ${server.address().port}`)
})
module.exports = app

Լուծող

'use strict'
const resolvers = {
  userInformation: ({ isLoggedIn }, { errorName }) => {
    if (!isLoggedIn) {
      throw new Error(errorName.UNAUTHORIZED)
    }
  
    return 'My username'
  },
 
  findUserByEmail: ({ email }, { errorName }) => {
    const re = /\S+@\S+\.\S+/;
    if (!re.test(email)) {
      throw new Error(errorName.INVALID_EMAIL)
    }
    return email
  }
}
module.exports = resolvers

Արդյունքներ

Ամբողջական ցուցադրություն՝https://github.com/EasyGraphQL/easygraphql-format-error/tree/master/example

Npm փաթեթ՝https://www.npmjs.com/package/easygraphql-format-error