How to handle body-parser errors in express nodejs

I find a web service on Node with the following data,

My request details:

{ "first_name":"surinder",, "last_name":"rawat", "email":" surinder.rawat@testcompany.com ", "phone":"1234567890", "password":"surinder", "user_type":"H", "device_type":"A" } 

and get the 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 a double comma to get this error. I want to know how to handle this error and show the user the error in the correct format

thanks

+6
source share
1 answer

From Documents -

You determine the last error handling middleware after the other app.use() and route the calls; eg:

 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!'); }); 
+4
source

Source: https://habr.com/ru/post/979762/


All Articles