Skip to main content
freelanceshack.com

Back to all posts

How to Print A Custom Message In GraphQL?

Published on
8 min read
How to Print A Custom Message In GraphQL? image

Best GraphQL Custom Message Tools to Buy in November 2025

1 GraphQL Best Practices: Gain hands-on experience with schema design, security, and error handling

GraphQL Best Practices: Gain hands-on experience with schema design, security, and error handling

BUY & SAVE
$39.99
GraphQL Best Practices: Gain hands-on experience with schema design, security, and error handling
2 Mastering GraphQL with Spring Boot: From Fundamentals to Production-Ready GraphQL Services

Mastering GraphQL with Spring Boot: From Fundamentals to Production-Ready GraphQL Services

BUY & SAVE
$3.99
Mastering GraphQL with Spring Boot: From Fundamentals to Production-Ready GraphQL Services
3 Mr. Pen- Wooden Geometry Set, 4 Pack, Triangle Ruler Set Square, Protractor Set, Protractors, Drafting Triangle, Drafting Tools & Drafting Kits, Geometry Kit, Drawing Tools

Mr. Pen- Wooden Geometry Set, 4 Pack, Triangle Ruler Set Square, Protractor Set, Protractors, Drafting Triangle, Drafting Tools & Drafting Kits, Geometry Kit, Drawing Tools

  • DURABLE WOODEN DESIGN FOR LONG-LASTING, RELIABLE USE.
  • CLEAR MARKINGS IN INCHES AND CENTIMETERS FOR PRECISION.
  • SMOOTH EDGES FOR A COMFORTABLE GRIP AND DAMAGE-FREE DRAWING.
BUY & SAVE
$4.99
Mr. Pen- Wooden Geometry Set, 4 Pack, Triangle Ruler Set Square, Protractor Set, Protractors, Drafting Triangle, Drafting Tools & Drafting Kits, Geometry Kit, Drawing Tools
4 Mr. Pen Metal Geometry Kit - 4Pack Set Square, Protractor, Aluminum Ruler, Drafting Triangles

Mr. Pen Metal Geometry Kit - 4Pack Set Square, Protractor, Aluminum Ruler, Drafting Triangles

  • CRAFTED IN THE USA: QUALITY AND PRECISION YOU CAN TRUST!
  • DURABLE ALUMINUM ENSURES LONG-LASTING, LIGHTWEIGHT PERFORMANCE.
  • VERSATILE FOR SCHOOLS, ARCHITECTS, AND ENGINEERS-MEASURE WITH EASE!
BUY & SAVE
$7.99
Mr. Pen Metal Geometry Kit - 4Pack Set Square, Protractor, Aluminum Ruler, Drafting Triangles
5 Mr. Pen- Professional Geometry Set, 15 pcs, Geometry Kit for Artists and Students, Geometry Set, Metal Rulers and Compasses, Drawing Tools, Drafting Supplies, Drafting Set, Drafting Tools and Kits

Mr. Pen- Professional Geometry Set, 15 pcs, Geometry Kit for Artists and Students, Geometry Set, Metal Rulers and Compasses, Drawing Tools, Drafting Supplies, Drafting Set, Drafting Tools and Kits

  • COMPLETE GEOMETRY SET: TOOLS FOR STUDENTS, TEACHERS, AND ARTISTS!

  • DURABLE PLASTIC CASE: EASY TO STORE AND CARRY, KEEPING TOOLS SAFE.

  • PERFECT GIFT: IDEAL FOR KIDS AND FRIENDS, VERSATILE FOR ALL USERS.

BUY & SAVE
$19.85
Mr. Pen- Professional Geometry Set, 15 pcs, Geometry Kit for Artists and Students, Geometry Set, Metal Rulers and Compasses, Drawing Tools, Drafting Supplies, Drafting Set, Drafting Tools and Kits
6 Bntyok Multifunctional Geometric Ruler 4 Pieces Geometric Ruler Drawing Ruler Template Ruler Measuring Ruler Geometric Drafting Tool for Student Architecture School and Office

Bntyok Multifunctional Geometric Ruler 4 Pieces Geometric Ruler Drawing Ruler Template Ruler Measuring Ruler Geometric Drafting Tool for Student Architecture School and Office

  • VERSATILE RULER SET: 4 MULTIFUNCTIONAL RULERS FOR ALL DRAWING NEEDS!
  • PRECISION DESIGN: CLEAR SCALES ENSURE ACCURATE, PROFESSIONAL RESULTS.
  • DURABLE QUALITY: LIGHTWEIGHT, STURDY, AND LONG-LASTING FOR DAILY USE.
BUY & SAVE
$9.29
Bntyok Multifunctional Geometric Ruler 4 Pieces Geometric Ruler Drawing Ruler Template Ruler Measuring Ruler Geometric Drafting Tool for Student Architecture School and Office
7 Nicpro 30PCS Professional Drafting Tools & Geometry Set with Case, Architect Protractor Set, Metal Mechanical Pencils, Pen, Scale Ruler Metal Ruler, 5 Drawing Templates for Interior Design House Plan

Nicpro 30PCS Professional Drafting Tools & Geometry Set with Case, Architect Protractor Set, Metal Mechanical Pencils, Pen, Scale Ruler Metal Ruler, 5 Drawing Templates for Interior Design House Plan

  • VERSATILE TEMPLATES: 5 REUSABLE TEMPLATES FOR EFFICIENT DESIGN WORK.

  • UPGRADED PENCILS: 4 MECHANICAL PENCILS FOR ALL YOUR DRAFTING NEEDS.

  • DURABLE CARRYING CASE: ORGANIZE TOOLS NEATLY; PERFECT FOR PROFESSIONALS.

BUY & SAVE
$28.99 $32.99
Save 12%
Nicpro 30PCS Professional Drafting Tools & Geometry Set with Case, Architect Protractor Set, Metal Mechanical Pencils, Pen, Scale Ruler Metal Ruler, 5 Drawing Templates for Interior Design House Plan
8 Mr. Pen Triangle Ruler, Protractor, Math Set - 3 Pack, Square Ruler, Protractor for Geometry

Mr. Pen Triangle Ruler, Protractor, Math Set - 3 Pack, Square Ruler, Protractor for Geometry

  • CLEAR, ETCHED MEASUREMENTS FOR PRECISE READING AND EASY USE.

  • DURABLE, HIGH-QUALITY TOOLS PERFECT FOR STUDENTS AND PROFESSIONALS.

  • VERSATILE GEOMETRY SET IDEAL FOR ARCHITECTS, ARTISTS, AND ENGINEERS.

BUY & SAVE
$6.99
Mr. Pen Triangle Ruler, Protractor, Math Set - 3 Pack, Square Ruler, Protractor for Geometry
9 Nicpro 21PCS Professional Drafting Tools & Geometry Set with Case, Architect Compass & Protractor Set, Metal Pencils, Pens, Scale Ruler Metal Ruler, 5 Drawing Templates for Interior House Plan Design

Nicpro 21PCS Professional Drafting Tools & Geometry Set with Case, Architect Compass & Protractor Set, Metal Pencils, Pens, Scale Ruler Metal Ruler, 5 Drawing Templates for Interior House Plan Design

  • COMPREHENSIVE SET OF TEMPLATES FOR ALL YOUR DESIGN NEEDS.
  • PRECISION TOOLS FOR ACCURATE DRAFTING AND FLAWLESS RESULTS.
  • CONVENIENT STORAGE CASE FOR EASY ORGANIZATION AND TRANSPORT.
BUY & SAVE
$25.99 $28.99
Save 10%
Nicpro 21PCS Professional Drafting Tools & Geometry Set with Case, Architect Compass & Protractor Set, Metal Pencils, Pens, Scale Ruler Metal Ruler, 5 Drawing Templates for Interior House Plan Design
+
ONE MORE?

To print a custom message in GraphQL, you can use the printError function provided by the graphql module. Here's how you can do it:

  1. Import the required modules:

const { graphql, printError } = require('graphql');

  1. Prepare your GraphQL schema and query:

// Define your GraphQL schema const schema = new GraphQLSchema({ ... });

// Define your GraphQL query const query = ` query { ...
} `;

  1. Execute the GraphQL query:

graphQL(schema, query) .then(result => { // Handle the result

if (result.errors) {
  console.error(printError(result.errors));
} else {
  console.log(result);
}

}) .catch(err => { // Handle the error console.error('Error occurred:', err); });

  1. Printing a custom error message:

if (result.errors) { result.errors.forEach(error => { console.error(printError({ ...error, message: `{Custom message: ${error.message}}`, // Modify the error message here })); }); }

In the above example, printing a custom message is done by modifying the message property of the error object. You can replace {Custom message: ${error.message}} with any custom message you want.

Note that the printError function formats and prints the errors in a user-friendly manner. It is not necessary to use this function if you just want to log the error as plain text without any formatting.

Remember to replace ... with your actual schema and query code.

How to log custom messages using middleware in GraphQL?

To log custom messages using middleware in GraphQL, you can create a custom middleware function that will be invoked for each GraphQL resolver execution. This middleware function can be responsible for logging custom messages based on your requirements.

Here's an example implementation of logging custom messages in middleware using the Apollo Server package:

  1. Install the necessary packages:

npm install apollo-server graphql

  1. Create a new file, e.g., graphqlMiddleware.js, and add the following code:

const { ApolloServer } = require('apollo-server'); const { makeExecutableSchema } = require('graphql-tools');

// Define your GraphQL schema and resolvers const typeDefs = ` type Query { hello: String } `;

const resolvers = { Query: { hello: () => 'Hello, world!', }, };

// Create a custom middleware function function loggingMiddleware(resolve, parent, args, context, info) { console.log('Custom message:', info.fieldName);

// Call the next middleware or resolver function return resolve(); }

// Create the executable schema with resolvers const schema = makeExecutableSchema({ typeDefs, resolvers });

// Create an Apollo Server instance with the middleware const server = new ApolloServer({ schema, context: ({ req }) => ({ // Apply the middleware to all resolvers req, allResolvers: schema.getResolvers(), middlewares: [loggingMiddleware], }), });

// Start the server server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });

  1. Run the server with the following command:

node graphqlMiddleware.js

  1. Now, when you make a GraphQL request, you should see the custom message being logged in the console for each resolved field.

Note that this example uses the Apollo Server package, but you can apply this concept to any GraphQL server implementation with middleware support. The key is to define a custom middleware function and apply it to the resolver execution chain.

How to include a custom message in GraphQL response?

To include a custom message in a GraphQL response, you can make use of the errors field in the response. Here's an example of how you can include a custom message in the response:

  1. Define a custom GraphQL error:

const { GraphQLError } = require('graphql');

class CustomGraphQLError extends GraphQLError { constructor(message, nodes, source, positions, path, originalError, extensions) { super(message, nodes, source, positions, path, originalError, extensions); } }

  1. In your resolver, throw a new instance of the custom error:

throw new CustomGraphQLError('Custom error message');

  1. Configure the GraphQL server's formatError option to handle your custom error:

const { ApolloServer } = require('apollo-server');

const server = new ApolloServer({ ... formatError: (err) => { if (err.originalError instanceof CustomGraphQLError) { return { message: err.message, code: 'CUSTOM_ERROR' // You can include any other custom fields or meta data as needed }; }

return err;

}, ... });

  1. Now, when the custom error is thrown in the resolver, it will be caught and formatted by the formatError function. The resulting response will include a custom message:

{ "errors": [ { "message": "Custom error message", "code": "CUSTOM_ERROR" // Any other custom fields or meta data you included } ] }

By utilizing this approach, you can add custom error messages or any other custom fields to the GraphQL response as needed.

How to send a custom message to the client in GraphQL?

In GraphQL, you can send custom messages to the client by using the GraphQLObjectType to define a custom type for your response and including a field for the custom message.

Here's an example:

const { graphql, GraphQLObjectType, GraphQLString, GraphQLSchema, } = require('graphql');

const MessageType = new GraphQLObjectType({ name: 'Message', fields: { text: { type: GraphQLString } } });

const Query = new GraphQLObjectType({ name: 'Query', fields: { hello: { type: MessageType, resolve: () => { return { text: 'Hello, world!' }; } } } });

const schema = new GraphQLSchema({ query: Query });

const query = ` query { hello { text } } `;

graphql(schema, query) .then(result => { const message = result.data.hello.text; console.log(message); // Output: "Hello, world!" });

In the above example, we define a custom type MessageType which includes a single field text of type GraphQLString. This type represents the custom message that will be sent to the client.

In the Query type, we define a field hello of type MessageType. The resolver function for this field returns an object with a text property, which contains the custom message we want to send to the client.

Finally, we execute the query using the graphql function, passing in the schema and query, and then extract and display the custom message from the result.

You can modify this example to include more custom fields in the MessageType or add more fields and types in your schema to suit your specific needs.

How to use variables in custom error messages in GraphQL?

To use variables in custom error messages in GraphQL, you can follow these steps:

  1. Define a custom error type in your GraphQL schema. This can be done by creating a new object type specifically for error messages.

type Error { message: String! code: String }

  1. Modify your resolver functions to include the appropriate error handling logic. You can use variables passed in by clients to generate customized error messages.

// Example resolver function resolve: (parent, args) => { if (args.input === 'invalid') { throw new Error(JSON.stringify({ message: `Invalid input: ${args.input}`, code: '500' })); } // ... }

  1. In your GraphQL server, handle the thrown errors and map them to your custom error type. You can do this using middleware or in your resolver functions.

// Example middleware app.use('/graphql', (req, res, next) => { return graphqlHTTP({ schema, graphiql: true, customFormatErrorFn: err => { if (err.originalError instanceof Error) { const parsedError = JSON.parse(err.originalError.message); return { message: parsedError.message, code: parsedError.code }; } // default format for non-custom errors return { message: err.message, code: '500' }; } })(req, res, next); });

  1. Now, when an error is thrown from a resolver function, it will be formatted according to the custom error type and returned to the client.

For example, if the input variable is set to 'invalid', the error message will be 'Invalid input: invalid', and the code will be '500'.

Note: The specific implementation may vary depending on the GraphQL server library you are using, but the concept remains the same.

What is the correct way to output a customized message in GraphQL?

In GraphQL, you can customize a message by defining a field with a specific Type. Here is an example of how to do it:

  1. Define a custom Type for the message:

type CustomMessage { message: String! }

  1. Create a query or mutation with the custom Type as the return value:

type Query { getCustomMessage: CustomMessage! }

type Mutation { createCustomMessage(message: String!): CustomMessage! }

  1. Implement the resolvers for the queries or mutations:

const resolvers = { Query: { getCustomMessage: () => { return { message: "This is a custom message" }; }, }, Mutation: { createCustomMessage: (parent, { message }) => { // Perform any necessary logic here return { message }; }, }, };

  1. Execute the query or mutation operation on your GraphQL server to retrieve or create a custom message:

query { getCustomMessage { message } }

mutation { createCustomMessage(message: "Hello World") { message } }

The server will respond with the customized message based on the query or mutation operation.