DEV Community


Posted on

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. :)

Top comments (0)