DEV Community

paruladitya
paruladitya

Posted on

2 1

Graphql and Parse Errors

Graphql errors may be caused by many different factors. Maybe its a server error- caused by a downstream API or database failure, or some other program bug. Or it could be a request error.

Request errors are caused by the client. Maybe its a bad request, a permission error, or a field type mismatch. But sometimes the cause is simpler- and paradoxically trickier to correct.

I ran into a similar problem recently. Anyone who has tried to send stringified JSONs or arrays into text fields with the intention of parsing them later can attest, that while this idea seems a clear-cut solution, things are often not so simple.

A major problem comes in the form of effectively escaping characters in strings. A simple object may work just fine with basic replace or escape, but as your object gets bigger and more complex, problems previously unseen stir up.

After a lot of trial and error and research, I found this piece of code that solved all of my problems.

String.prototype.escapeSpecialChars = function () {
  return this.replace(/\\/g, "\\\\")
    .replace(/\n/g, "\\n")
    .replace(/\r/g, "\\r")
    .replace(/\t/g, "\\t")
    .replace(/\f/g, "\\f")
    .replace(/"/g, '\\"');
};
Enter fullscreen mode Exit fullscreen mode

Simply use it on a stringified object.

stringObj = JSON.stringify(obj)
let escapedStringObj = stringObj.escapeSpecialChars();
Enter fullscreen mode Exit fullscreen mode

While the method of stringifying and later parsing objects is less than ideal, and far from my recommendation, sometimes it really may be the simplest way. In case you ever feel the need to embark on such an endeavor, remember to escape responsibly! I hope this bit of code helps you as much as it did for me. :)

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay