how to handle body-parser errors in express nodejs
Asked Answered
R

2

17

I am hitting a web service on Node with following data,

MY request data is:

{
"first_name":"surinder",,
"last_name":"rawat",
"email":"[email protected]",
"phone":"1234567890",
"password":"surinder",
"user_type":"H",
"device_type":"A"
}

and getting following error:

Connect
400 SyntaxError: Unexpected token ,
   at Object.parse (native)
   at parse (/home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/typs
   /json.js:76:17)
   at /home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/read.js:98:18
   at IncomingMessage.onEnd (/home/surinder/workspace/HappyHakka/node_modules/body-parser
   /node_modules/raw-body/index.js:136:7)
   at IncomingMessage.g (events.js:180:16)
   at IncomingMessage.emit (events.js:92:17)
   at _stream_readable.js:943:16
   at process._tickCallback (node.js:419:13)

I intentionally used double comma to get this error. I want to know how to handle this error and show user an error in a proper format

Thanks

Reareace answered 17/12, 2014 at 8:12 Comment(4)
The last callback in your middleware stack should be your error handler, which will catch these errors. DocsDyke
Thanks that worked. For those who don't get it. use, app.use(function(err, req, res, next){ // logic }); after app.use(bodyParser());Reareace
You could make it an answer thoughHumism
"first_name":"surinder",, - why two commas?Vorster
M
14

From the Docs -

You define error-handling middleware last, after other app.use() and routes calls; for example:

var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(function(err, req, res, next) {

  // error handling logic
  console.error(err.stack);
  res.status(500).send('Something broke!');

});
Marc answered 14/9, 2016 at 12:3 Comment(2)
I'd recommend placing a more specific error handler in the router middleware chain right after the bodyParser to specifically handle errors occurring at that point. While leaving more generic error handling middleware for later on in the chain.Kilogram
@Kilogram I cannot agree more with this, however everybody always seems to be okay with handling common errors like syntaxError as if it could not happen anywhere else than in the parser.Fugacity
I
2

its related to body-parser and raw-body packages if you want to solve this issue in a more robust why and handle all errors thrown from body parser use this middleware

https://github.com/ntedgi/express-body-parser-error-handler

$ npm i express-body-parser-error-handler

it will handle all common errors thrown from body-parser for example

'encoding.unsupported', 'entity.parse.failed', 'entity.verify.failed', 'request.aborted', 'request.size.invalid', 'stream.encoding.set', 'parameters.too.many', 'charset.unsupported', 'encoding.unsupported', 'entity.too.large'

usage example :

const bodyParserErrorHandler = require('express-body-parser-error-handler')
const { urlencoded, json } = require('body-parser')
const express = require('express')
const app = express();
router.route('/').get(function (req, res) {
    return res.json({message:"🚀"});
});

// body parser initilization
app.use(urlencoded({extended: false, limit: defaultLimitSize}));
app.use('/', json({limit: '250'}));

// body parser error handler
app.use(bodyParserErrorHandler());
app.use(router);
...
Ibarra answered 25/12, 2021 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.