0

I want to change http status code when throw error like with "throw new Error("this is my error.")"? I want this because i should return localized error message in frontend. How can do this, is it possible?

I tried this but i got the this error:
send error in query/mutation:

throw new Error("Not Authorized.")
graphql_router.use("/", graphqlHTTP((req, res, graphQLParams) => {
    return {
        schema: schema,
        graphiql: process.env.NODE_ENV === 'development',
        contextValue: { ip: req.ip },
        customFormatErrorFn: (error) => {
            try {
                return res.status(500).json({ error: error.message })
            } catch {
                return error;
            }
        },
    }
}));

error:

backend/node_modules/express/lib/response.js:1150
    : JSON.stringify(value);
           ^

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Socket'
    |     property '_writableState' -> object with constructor 'WritableState'
    |     property 'afterWriteTickInfo' -> object with constructor 'Object'
    --- property 'stream' closes the circle
    at JSON.stringify (<anonymous>)
    at stringify (/Users/tarikulkerjs/Desktop/projects/blindlook/backend/node_modules/express/lib/response.js:1150:12)
    at ServerResponse.json (/Users/tarikulkerjs/Desktop/projects/blindlook/backend/node_modules/express/lib/response.js:271:14)
    at graphqlMiddleware (/Users/tarikulkerjs/Desktop/projects/blindlook/backend/node_modules/express-graphql/index.js:198:22)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v18.16.0
[nodemon] app crashed - waiting for file changes before starting...

1 Answers1

0

You can use GraphQLError in mutaions or queries.

import { GraphQLError } from 'graphql';

And throw the GraphQLError like this:

throw new GraphQLError("User not found", {
  extensions: { code: "NOT_FOUND", http: { status: 404 } },
});
myrn
  • 153
  • 5