Git Product home page Git Product logo

Comments (11)

guikubivan avatar guikubivan commented on May 23, 2024 3

Anybody can show an example of how to do this:

Return 400 on validation error; 500 on any other error

I wasn't sure if closing the issue meant it was addressed and if it's possible to do this now.

from express-graphql.

mnylen avatar mnylen commented on May 23, 2024 1

Still, although this hack allows me to sanitize the error messages, it doesn't give me an easy way to access the parsed query and variables from request body / query string.

Ideally I'd like to do something like:

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
  writeResponse: (query, variables, result, req, res) => {
    if (result.errors) {
      logger.error("Error executing query: " + query + "\nVariables:\n" + JSON.stringify(variables) + "\nErrors:\n" + JSON.stringify(result))
      res.send(500).json(sanitizeErrors(result))
    } else {
      res.send(200).json(result)
    }
  }
})

from express-graphql.

plee-nm avatar plee-nm commented on May 23, 2024 1

@guikubivan I just proved it out locally not sure if it is a good idea. It doesn't look bad to me but I would love feedback from anyone.

  graphqlHTTP(async (request, response) => ({
    formatError: (error: GraphQLError) => {
      response.status(400);
      ...

A more real life example would do something like:

 import { formatError, GraphQLError } from 'graphql';

  graphqlHTTP(async (request, response) => ({
    formatError: (error: GraphQLError) => {
      const { originalError } = error;
      // add custom error logic
      if(isValidationError(originalError) {
          response.status(400);
      }
      return formatError(error);
  }))

from express-graphql.

mnylen avatar mnylen commented on May 23, 2024

A nasty hack that I'm currently using to achieve this:

app.use('/graphql', function(req, res, next) {
  let end = res.end

  res.end = function(chunk, encoding) {
    res.end = end

    let contentType = res.get('content-type') || 'text/html'
    if (contentType.indexOf('application/json') === 0) { // don't overwrite graphiql responses
      let response = JSON.parse(chunk)

      if (response.errors) {
        let validationErrors = response.errors
          .filter(({message}) => message.indexOf('Syntax Error') !== -1 || message.indexOf('Cannot query field') !== -1)
          .map(({message}) => ({ message }))

        if (validationErrors.length > 0) {
          res.status(400).json({ errors: validationErrors })
        } else {
          res.status(500).json({ errors: [{ message: "Query could not be executed" }] })
        }
      } else {
        res.end(chunk, encoding)
      }
    } else {
      res.end(chunk, encoding)
    }
  }

  return next()
})

from express-graphql.

leebyron avatar leebyron commented on May 23, 2024

Those use cases sound like things we should support, but post-processing the response is not how I would prefer them implemented.

The goal of this package is to create a standardized http interface for GraphQL, which post-processing could easily circumvent.

I'll propose some paths forward:

Log errors

graphql-js could already use a comprehensive logging interface, regardless of if it is accessed via http. I'd like to focus a logging interface on graphql-js itself, and just make that easy to interface via express-graphql.

Sanitize error messages from any sensitive information

Similar to the above. Sanitizing sensitive info in errors seems like an issue regardless of the access mechanism.

Return 400 on validation error; 500 on any other error

This just seems like the right thing to do, let's standardize that.

Add custom response headers based on response body

Could you elaborate on this? What custom headers are you planning to send?

from express-graphql.

leebyron avatar leebyron commented on May 23, 2024

Return 400 on validation error; 500 on any other error.

Turns out this was already the current behavior, but there were some other underspecified error codes which should now be correct as of 546191d

from express-graphql.

mnylen avatar mnylen commented on May 23, 2024

Yes, I agree now that post processing probably isn't the best way to approach this. If logging errors and sanitizing them from responses could be baked directly into graphql-js, that would fully solve my use case.

Add custom response headers based on response body

Could you elaborate on this? What custom headers are you planning to send?

Actually, this was just something I grabbed from another issue - seemed like something the post processing could also fix.

from express-graphql.

vitosamson avatar vitosamson commented on May 23, 2024

Could you elaborate on this? What custom headers are you planning to send?

I have a use case where my GraphQL resolver hits another HTTP service, which returns certain headers for data like pagination. I'd need to forward those headers to the GraphQL client that made the initial request.

Is that currently supported without @mnylen's hack?

from express-graphql.

colllin avatar colllin commented on May 23, 2024

@vitosamson How would you know which field the pagination headers applied to?

from express-graphql.

vitosamson avatar vitosamson commented on May 23, 2024

you're right - I realized that limitation after I posted the comment. I wound up wrapping paginatable types so that they return both the list and the pagination data, and my HTTP resolvers just grab the headers from the response and add them onto the returned data. A query winds up looking like query { thingList { things {}, pagination }}, which is a bit cumbersome but flexible.

from express-graphql.

leebyron avatar leebyron commented on May 23, 2024

@vitosamson - you should check out https://facebook.github.io/relay/docs/graphql-connections.html where there are in depth docs on best practices for pagination.

@mnylen - I think you're right that the best solution here is to allow GraphQL.js the ability to operate on errors to do this sort of thing. Tracking that in graphql/graphql-js#284

That said, there are still some errors that occur within this package, so having the ability to sanitize at the last step is totally reasonable.

from express-graphql.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.