Socrates
Socrates

Reputation: 9574

body-parser catch bad JSON

Is it possible to catch bad JSON syntax in body-parser?

The following code shows my attempt. The problem is that I can't access any err.status as I get the response:

SyntaxError: Unexpected token ] in JSON at position 57...

This is brought to the caller as a HTML page. I would rather catch that error and format a nice JSON as a response.

The code attempt:

class ExampleServer extends Server {
    constructor() {

        ...

        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({extended: true}));
        this.app.use((err) => {
            if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
                Logger.Err('Bad JSON.');
            }
        });

        ...
    }
}

The broken JSON I send through the POST body:

{
    "numberValue": 6,
    "requiredValue": "some string here"]
}

The versions of body-parser and express I use:

"body-parser": "^1.19.0",
"express": "^4.17.1",

How can I catch the broken JSON error?

Upvotes: 2

Views: 124

Answers (1)

Eoaioaou
Eoaioaou

Reputation: 61

Yes, it is possible to instruct Express to catch bad JSON syntax. Try to adapt this code:

this.app.use((error: any, req: any, res: any, next: any) => {
  if (error instanceof SyntaxError) {
    // Catch bad JSON.
    res.sendStatus(400);
  } else {
    next();
  }
});

Upvotes: 2

Related Questions