In ExpressJS app final app.use which is using for error handling
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log('as',typeof err);
// res.render('error1', {
// message: err.message,
// error: {}
// });
res.json(err.message)
});
When I log err it print as {} ,but when I log err.message it show string like 'obj is not defined'. Why this happens and how I can see all the keys of err object like message .
app.use(function(err, req, res, next) {
if(err){
res.json(err)
}
else{
//err is {}
}
});
If it is not error, then the err will be null.
Related
I have a basic Express app which has a few routes.
One is as such:
router.post('/upload', (req, res) => {
let audioFile = req.files.audioFile;
const file = __dirname + '/../' + req.body.uploadLocation + audioFile.name;
mp3.mv(file, function(err) { // <--- HERE
if (err) {
return res.status(500).send(err);
}
res.send('File uploaded!');
});
});
Now, if you would try to upload a file to this route you would get a 500 and that's it. The highlighted line is a result of me changing variable name. Is there any way to get it so that it prints out the actual error? I am tripped up by this so often and it would make it an awful lot quicker if the terminal output just told me the normal JS error like it does on the browser or when I'm running node normally.
In Express there is middleware to handle errors. In the a base setup of express you'll find:
// error handler
app.use(function(err, req, res, next) {
...
// render the error page
res.status(err.status || 500);
res.json({ error: err });
});
Just add a console.error there:
// error handler
app.use(function(err, req, res, next) {
console.error(err.stack); // <- HERE
...
// render the error page
res.status(err.status || 500);
res.json({ error: err });
});
I am trying to write a middleware to handle errors. But I cannot figure out how to send the correct format to my frontend. Below I am going to list all of my attempts in hopes of helping you help me.
Attempt 1
app.use(function(err, req, res, next) {
const formatted = err;
res.send(formatted)
});
result in postman
{ "code": 422 }
Attempt 2
app.use(function(err, req, res, next) {
const formatted = `${err}`;
res.send(formatted)
});
result (postman)
Error: Request returned error code: 422 and body: {"status":422,"title":"The display name: build_id has already been used on this product.","type":"https://developer.bigcommerce.com/api#api-status-codes","errors":{"display_name":"The display name: build_id has already been used on this product."}}
That is the data i want but i need it in json
Question Why is there more data revealed after string interpolation? How can i format it to json?
You're probably looking for res.json(err) if I had to guess?
https://expressjs.com/en/api.html#res.json
EDIT: Full example:
app.use(function(err, req, res, next) {
if (err) res.json(err)
});
You can do it in this way
app.use(function(err, req, res, next) {
if (err) {
res.json({
status: "error",
error: `${err}` // <-- edited
});
} else {
next();
}
});
I am getting this error on my code, and I don't know how to fix it ?
DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My code so far:
router.post('/users/*', (req, res) => {
User.create(new User({
email: req.body.identity.user_email,
authUserId: req.body.identity.user_id
}))
res.json(console.log("User Created"))
})
router.get('/users/:id', (req, res, next) => {
User.findOne({authUserId: req.params.id}, (err, userr) => {
if(err) {
return next(err);
} else if (userr) {
res.json(userr.email);
} else {
res.json(null)
}
});
});
Can someone help me get rid of this error.
Thnx in advance! :)
I guess your application's entry point is app.js. So, as you are forwarding error as return next(err);, there should be someone who will catch that and handle.
generally I place handler on app.js before listener function-
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
In a route I have this:
if (elements.length <= 0) {
var msg = 'no elements found';
console.error(msg);
var err = new Error('Not found');
err.status = 404;
err.message = msg;
next(err);
}
console.log('Found ' + elements.length + ' elements');
res.setHeader('Content-Type', 'application/json'); /*error*/
res.status(200).json(elements);
res.end();
The error handler that is defined last in app.js:
// development error handler
app.use(function(err, req, res, next) {
res.type('application/json');
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
I see that the error is sent as response in json.
But I get this error on the line marked with /error/:
Can't set headers after they are sent.
Why is express returning from the error handler?
I can see that it is continuing the execution of the route (from the console.log)
Why is it continuing execution of the route?
Inside if statement correct:
return next(err);
My code looks like this
app.get('/', function(req, res, next) {
if (id==8) {
res.send('0e');
} else {
next();
}
});
app.use(function(err, req, res, next){
res.send(500, '<h1>Oops! what happened?</h1>');
});
So. the next() function is called the message Ooops! what happened should appear on screen but instead a message ' Cannot GET / ' appears
You can use node.js built in uncaught exception, just put this code inside your server.js
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
//you can also email this error
});
or follow this link
http://masashi-k.blogspot.com/2012/12/express3-global-error-handling-domain.html
Error handlers are only called if next() was called with an Error object.
So to trigger your error handler you'd have to do:
app.get('/', function(req, res, next) {
if (id==8) {
res.send('0e');
} else {
next(new Error('Fake error occurred'));
}
});
app.use(function(err, req, res, next){
res.send(500, '<h1>Oops! what happened?</h1>');
});