Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Node.js Error Management

Other topics

Creating Error object

new Error(message)

Creates new error object, where the value message is being set to message property of the created object. Usually the message arguments are being passed to Error constructor as a string. However if the message argument is object not a string then Error constructor calls .toString() method of the passed object and sets that value to message property of the created error object.

var err = new Error("The error message");
console.log(err.message); //prints: The error message
console.log(err);
//output
//Error: The error message
//    at ... 

Each error object has stack trace. Stack trace contains the information of error message and shows where the error happened (the above output shows the error stack). Once error object is created the system captures the stack trace of the error on current line. To get the stack trace use stack property of any created error object. Below two lines are identical:

console.log(err);
console.log(err.stack);

Throwing Error

Throwing error means exception if any exception is not handled then the node server will crash.

The following line throws error:

throw new Error("Some error occurred"); 

or

var err = new Error("Some error occurred");
throw err;

or

throw "Some error occurred";

The last example (throwing strings) is not good practice and is not recommended (always throw errors which are instances of Error object).

Note that if you throw an error in your, then the system will crash on that line (if there is no exception handlers), no any code will be executed after that line.

var a = 5;
var err = new Error("Some error message");
throw err; //this will print the error stack and node server will stop
a++; //this line will never be executed
console.log(a); //and this one also

But in this example:

var a = 5;
var err = new Error("Some error message");
console.log(err); //this will print the error stack
a++; 
console.log(a); //this line will be executed and will print 6

try...catch block

try...catch block is for handling exceptions, remember exception means the thrown error not the error.

try {
    var a = 1;
    b++; //this will cause an error because be is undefined
    console.log(b); //this line will not be executed
} catch (error) {
    console.log(error); //here we handle the error caused in the try block
}

In the try block b++ cause an error and that error passed to catch block which can be handled there or even can be thrown the same error in catch block or make little bit modification then throw. Let's see next example.

try {
    var a = 1;
    b++;
    console.log(b);
} catch (error) {
    error.message = "b variable is undefined, so the undefined can't be incremented"
    throw error;
}

In the above example we modified the message property of error object and then throw the modified error.

You can through any error in your try block and handle it in the catch block:

try {
    var a = 1;
    throw new Error("Some error message");
    console.log(a); //this line will not be executed;
} catch (error) {
    console.log(error); //will be the above thrown error 
}

Contributors

Topic Id: 8590

Example Ids: 26859,26872,26873

This site is not affiliated with any of the contributors.