Reputation: 309
I'm creating an application that only accepts a body type of json and uses body-parsers and express. The problem that keeps showing up is if I send an invalid json body, then my program will throw a stupid error back to the user, and in the console. How would I prevent this console error and reject a request with an improper JSON body.
Thanks in advance, Avery.
PS. Here is some example code to show what I'm doing:
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.json());
app.post('/test', function(req, res){
res.status(200).send("Hi");
});
app.listen(8081, function(){
console.log("Server is running");
});
Upvotes: 5
Views: 3976
Reputation: 5707
body parser throw all kind of errors 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'
if you want a more robust solution use this middleware
https://www.npmjs.com/package/express-body-parser-error-handler
$ npm i express-body-parser-error-handler
for 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('/', json({limit: '250'}));
// body parser error handler
app.use(bodyParserErrorHandler());
app.use(router);
...
Upvotes: 0
Reputation: 36319
You need to attach some error handling middleware to your app. How you handle that error is up to you, but as an example of how you'd do it:
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.json());
// this is a trivial implementation
app.use((err, req, res, next) => {
// you can error out to stderr still, or not; your choice
console.error(err);
// body-parser will set this to 400 if the json is in error
if(err.status === 400)
return res.status(err.status).send('Dude, you messed up the JSON');
return next(err); // if it's not a 400, let the default error handling do it.
});
app.post('/test', function(req, res){
res.status(200).send("Hi");
});
app.listen(8081, function(){
console.log("Server is running");
});
Upvotes: 9