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: {}
});
});
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 });
});
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.
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);
I'm trying to convert an existing node.js project from javascript to typescript. I've been using the default 404 error catcher from the Visual Studio Express 4 template:
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
However, I'm getting the following error message:
Property 'status' does not exist on type 'Error'.
I get a similar message if I try and invoke the Error's .stack property:
Property 'stack' does not exist on type 'Error'.
Does anyone know what's going on here?
Edit: Steve Fenton points out that I could just put the error status on the response object. However, my error handling mechanism uses a two-step process:
Create the 404 error and set its status
Hand it on to the following generic handler:
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
So the error status is first set on the Error object, then read back by the error handler to decide how to handle the error.
Extend global Error
You can tell TypeScript that for your use case Error might have a status on it:
interface Error {
status?: number;
}
So you get:
interface Error {
status?: number;
}
var err = new Error('Not Found');
err.status = 404;
Alternative
Put the status on the res and send the err. For Example:
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
res.status(404); // using response here
next(err);
});
The best way in my opinion, is not to disable type checks by setting the error to any, or creating a new Error type, since one already exists in #types/node.
Instead, you should extend that error type:
interface ResponseError extends Error {
status?: number;
}
import * as express from 'express';
interface Error {
status?: number;
message?: string;
}
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
You put the error code on the response...
app.use(function (req, res, next) {
var err = new Error('Not Found');
res.status(404)
next(err);
});
This is generally a question of how to lazily initialize objects in Typescript.
The ideal way to do this is:
interface ErrorWithStatus extends Error {
status: string
}
let foo = new Error() as ErrorWithStatus;
foo.status = '404';
Using any, or interfaces with nullable fields, leave you with subpar and weak contracts.
If I am not mistaken it is always best to get the type that is actually expected. I couldn't find any hard support that I am right, but I use:
import createError, { HttpError } from 'http-errors';
and to be complete for all types I also import the parameter types of use:
import express, { Request, Response, NextFunction } from 'express';
The actual function I use then looks like this:
app.use((err: HttpError, req: Request, res: Response, next: NextFunction) => { ... }
In your case if you want to create your own error:
app.use((req: Request, res: Response, next: NextFunction) => {
next(createError(404));
});
or closer to your code:
app.use((req: Request, res: Response, next: NextFunction) => {
let err = new HttpError('Not found');
err.status = 404;
next(err);
});
Another option in TypeScript:
let err: any;
err = new Error();
err.status = 404;
Another option in TypeScript:
const err: { status?: number, message:string } = new Error('Not Found');
err.status = 404;
I just went for
var err = new Error('Not Found');
err['status'] = 404;
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>');
});