Note that there are some explanatory texts on larger screens.

plurals
  1. POCatch express bodyParser error
    primarykey
    data
    text
    <p>I want to catch the error from the bodyParser() middleware when I send a json object and it is invalid because I want to send a custom response instead of a generic 400 error.</p> <p>This is what I have and it works:</p> <pre><code>app.use (express.bodyParser ()); app.use (function (error, req, res, next){ //Catch bodyParser error if (error.message === "invalid json"){ sendError (res, myCustomErrorMessage); }else{ next (); } }); </code></pre> <p>But this seems to me a very ugly approach because I'm comparing the error message which could change in future express versions. There's any other way to catch bodyParser() errors?</p> <p>EDIT:</p> <p>This is the error when the request body has an invalid json:</p> <pre><code>{ stack: 'Error: invalid json\n at Object.exports.error (&lt;path&gt;/node_modules/express/node_modules/connect/lib/utils.js:55:13)\n at IncomingMessage.&lt;anonymous&gt; (&lt;path&gt;/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)\n at IncomingMessage.EventEmitter.emit (events.js:92:17)\n at _stream_readable.js:872:14\n at process._tickDomainCallback (node.js:459:13)', arguments: undefined, type: undefined, message: 'invalid json', status: 400 } </code></pre> <p>Pretty printed stack:</p> <pre><code>Error: invalid json at Object.exports.error (&lt;path&gt;/node_modules/express/node_modules/connect/lib/utils.js:55:13) at IncomingMessage.&lt;anonymous&gt; (&lt;path&gt;/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71) at IncomingMessage.EventEmitter.emit (events.js:92:17) at _stream_readable.js:872:14 at process._tickDomainCallback (node.js:459:13) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload