node.js handling variable undefined error through middleware - node.js

I have a node.js express app, and i'd like to catch any
<variable> is not defined
or
<object> does not have property <propertyname>
When i run the project locally, and a programmable error occurs I get these messages in the console and the request gets disposed. I want to handle them in the winston logger instead.
Thanks in advance

Removing dependencies from your code and testing with minimum reproducible snippet seem to work for me.
Update
Unhandled rejections can be handled using unhandledRejection
var express = require('express'),
path = require('path');
process.on('uncaughtException', function(err) {
console.log('uncaught exception', err);
}).on('unhandledRejection', (reason, p) => {
console.log('unhandledRejections reason', reason);
}).on('warning', (warning) => {
console.log(`warning, ... ${warning}`);
});
var app = express();
app.use('/api/subscriber', (req, res) => {
console.log('inside API');
return new Promise((resolve, reject)=>{
console.log(undeclaredVariable); // should error
res.status(200).send({
msg: 'hello world'
});
});
});
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(process.env.PORT || 5000); // Listen for requests
It logs
inside API
unhandledRejections reason [ReferenceError: undeclaredVariable is not defined]

Related

Express error handling - app crashes when error is thrown instead of going into the error handler

I have a problem with my node app. I set up an error handling middleware and when I throw an error in the controller, the app crashes instead of going into the error handler.
ErrorHandler.js
const mongoose = require("mongoose");
exports.ErrorHandler = (err, req, res, next) => {
console.log(err);
if (err instanceof mongoose.Error.ValidationError) {
return res.status(422).json(err.errors);
}
if (err instanceof mongoose.Error.CastError) {
return res.status(404).json({ message: "Resource not found" });
}
return res.status(500).json(err);
};
AuthController.js
static init = async (req, res) => {
throw new NotFoundError("Not found");
}
I didn't know how you're calling the ErrorHandler and if you're using express, but I think you're using it. Although I think I can give to you a simple example of usage of ErrorHandler as middleware:
function errorHandler(error, req, res, next) {
res.status(error.status || 500);
res.send({
error: {
message: error.message,
},
});
}
// Error-handling middleware
app.use(errorHandler);
//example
app.get('/', function (req, res, next) {
next(new Error('Error for understanding the ErrorHandler'));
});
In this example your app won't crashes.
Please read this official guide to complete understand how it works: https://expressjs.com/en/guide/error-handling.html

What are different between next(error) and throw new Error in Express framework?

Can someone explain to me about the different between two ways exception error handling in code Express JS below:
const express = require('express');
const app = express();
app.get('/test', (req, res, next) => {
// the first way:
throw new Error('my error message');
// the second way:
next(new Error('my error message'));
});
app.use((err, req, res, next) => {
res.status(err.status || 500).send(err.message || 'Internal Server Error');
});
app.listen(3000, () => console.log('Welcome to ExpressJS'));
It returns the same result handled by error middleware but what is the difference here?
Nothing, based on the source code.
try {
fn(req, res, next);
} catch (err) {
next(err);
}

How to avoid internal server error without using try catch clause in node js?

Server.js file
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();
var os = require('os');
//app.use(logger('dev'));
app.use(bodyParser.json());
app.all('/*', function (req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
// Auth Middleware - This will check if the token is valid
// Only the requests that start with /api/v1/* will be checked for the token.
// Any URL's that do not follow the below pattern should be avoided unless you
// are sure that authentication is not needed
//app.all('/api/v1/*', [require('./middlewares/validateRequest')]);
app.use('/', require('./routes')); // Write url in the routes.js file
app.use(function (err, req, res, next) {
if (!err) {
return next();
}
else {
return next();
}
});
//404 error handler
// If no route is matched by now, it must be a 404
app.use(function (req, res, next) {
var err = new Error('URL Not Found');
err.status = 404;
var date = new Date();
next(err);
});
// Start the server
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + server.address().port);
});
I have read to handle internal server error
Do like that. I even tried that too but it won't run as I wanted
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err.message+' w');
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: {}
});
});
How to avoid that so that the server won't shot down ?
Tried that link too https://expressjs.com/en/guide/error-handling.html , http://code.runnable.com/UTlPPF-f2W1TAAEU/error-handling-with-express-for-node-js
For express middleware error handling
Catch 404 and forward to error handler
app.use(function(req, res) {
res.status(404).send({
error: 'Not found'
});
});
if (app.get('env') === 'development') {
app.use(function(error, req, res, next) {
debug('http_status: %d, %s', error.status || 500, error.message);
next(error);
});
}
app.use(function(error, req, res) {
res.status(error.status || 500).send({
error: 'Internal server error'
});
});
Catch the uncaught errors that weren't wrapped in a domain or try catch statement
Note: Do not use this in modules, but only in applications, as otherwise, we could have multiple of these bound
process.on('exit', function(code) {
});
process.on('uncaughtException', function(err) {
console.log(err)
});
process.on('SIGINT', function() {
process.exit(0);
});

NodeJS - Why POST after GET doesn't work in express app?

This is app have only GET /test, it doesn't have POST /test yet. I'm uploading binary file 1.dat to it and it should return answer with '404', but seems I'm recieving ECONNRESET error instead.
var express = require('express');
var app = express();
var expect = require('expect.js');
var request = require('supertest');
var router = express.Router({
caseSensitive: true,
strict: true
});
router.get('/', function(req, res, next) {
res.send('test');
});
app.use('/test', router);
app.use(function(req, res, next) {
res.send('404');
});
Promise.resolve().then(function() {
var agent = request(app);
return new Promise(function(resolve, reject) {
agent
.get('/test')
.expect(200)
.end(function(err) {
if (err) {
return reject(err);
}
resolve(agent);
});
});
}).then(function(agent) {
return new Promise(function(resolve, reject) {
agent
.post('/test')
.attach('tmp', new Buffer([1, 2, 3]), '1.dat')
.expect(404)
.end(function(err, res) {
if (err) {
return reject(err);
}
resolve();
});
});
}).then(function() {
process.exit(0);
}).catch(function(err) {
console.log(err.stack);
process.exit(1);
});
But why it throws an error when validating .expect(404):
[TypeError: Cannot read property 'status' of undefined]
You don't send a status 404 but a string in your body.
app.use(function(req, res, next) {
res.status(404).end();
});

Express js error handling

I'm trying to get error handling running with express but instead of seeing a response of "error!!!" like I expect I see "some exception" on the console and then the process is killed. Is this how error handing is supposed to be setup and if so is there another way to catch errors?
var express = require('express');
var app = express();
app.use(function(err, req, res, next) {
console.log("error!!!");
res.send("error!!!");
});
app.get('/', function(request, response) {
throw "some exception";
response.send('Hello World!');
});
app.listen(5000, function() {
console.log("Listening on 5000");
});
An example app/guide on error handling is available at
https://expressjs.com/en/guide/error-handling.html
However should fix your code:
// Require Dependencies
var express = require('express');
var app = express();
// Middleware
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the next middleware (your error reporter)
app.use(function(err, req, res, next) {
if(!err) return next(); // you also need this line
console.log("error!!!");
res.send("error!!!");
});
// Routes
app.get('/', function(request, response) {
throw "some exception";
response.send('Hello World!');
});
// Listen
app.listen(5000, function() {
console.log("Listening on 5000");
});
A few tips:
1) Your code wasn't working because your error handler middleware was run before your route was reached, so the error handler never had a chance to have the error passed to it. This style is known as continuation passing. Put your error handler last in the middleware stack.
2) You should shut down the server when you have an unhandled error. The best way to do that is to call server.close(), where server is the result of doing var server = http.createServer(app);
Which means, you should do something like this:
var server = http.createServer(app);
app.use(function(err, req, res, next) {
console.log("error!!!");
res.send("error!!!");
server.close();
});
You should probably also time out the server.close(), in case it can't complete (your app is in an undefined state, after all):
var server = http.createServer(app);
app.use(function(err, req, res, next) {
console.log("error!!!");
res.send("error!!!");
server.close();
setTimeout(function () {
process.exit(1);
}, 3*1000);
});
I made a library that does all this for you, and lets you define custom responses, including specialized error views, static files to serve, etc...:
https://github.com/ericelliott/express-error-handler
I had the same problem and couldn't figure out what was wrong.
The thing is if you have the express errorHandler defined then your custom error handler is never being called.
If you have the next code, simply remove it:
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
Worked for me:)
Installing express install connect-domain, then something like this:
var express = require("express"),
connectDomain = require("connect-domain"),
app = express(),
errorHandler;
// Our error handler
app.use(connectDomain());
errorHandler = function (err, req, res, next) {
res.send(500, {
"status": "error",
"message": err.message
});
console.log(err);
};
Then when setting up your endpoints, tack errorHandler on the end in a use():
app.get("/some/data", function (req, res) {
// ... do some stuff ...
res.send(200, "Yay! Happy Success!");
}).use(errorHandler);
Create an error function:
function throwError(status, code, message) {
const error = new Error(message);
error.name = '';
error.status = status;
error.code = code;
throw error;
}
e.g.
throwError(422, 'InvalidEmail', '`email` should be a valid email address')
We assign name to '' so that when we toString the error it doesn't prepend it with "Error: "
As mentioned if you're using express you can create a special error handling middleware by specifying 4 arguments:
app.use((err, req, res, next) => {
if (err) {
res.status(err.status || 500).json({ code: err.code || 'Error', message: err.toString() });
}
});
If you're not using express or otherwise prefer, add that code to your catch handler instead.
Why?
Modern apps handle JSON, throwing errors in JSON makes more sense and results in cleaner UI code.
You should not only throw error messages because they are imprecise to parse. What if the UI is a multilingual app? In that case they can use the code to show a localized message.
Found that recipes from here and even in official documentation brake logging for advanced loggers like pino-http (at least for latest express4). Problem appears when you write like this:
app.use((err, req, res, next) => {
if (!err) {
return next();
}
res.status(err.status || 500).json({ error });
});
Express "thinks" that it's normal result and logger does not log error.
{
...
"res":{"status":400},
"msg":"request completed"
}
Fix here (the first line):
res.err = err;
res.status(err.status || 500).json({ error });
Log output after the fix:
{
...
"res":{"status":400},
"msg":"request errored",
"err":{"type":"Error","message":"Some error","stack":"..skip.."}
}

Resources