Obviously occuring errors is normal in any application. When error occurs, Node.js generates four categories of errors:
- Standard JavaScript errors such as
<EvalError>
,<SyntaxError>
,<RangeError>
,<ReferenceError>
,<TypeError>
, and<URIError>
. - System errors such as attempting to open a file that does not exist or attempting to send data over a closed socket.
- User-specified errors triggered by application code.
- Assertion errors are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur.
Now let's take an example of Javascript ReferenceError error
try {
let x = 1;
z = x + y;
} catch (err) {
console.log(err);
}
JavaScript try...catch
function tries to run blocks of code and through error if occurs. This will through error because we don't have defines y.
ReferenceError: y is not defined
at Object.<anonymous> (/var/www/html/event.js:4:13)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
You can use err.message property to returns only error message instead of possible error files.
console.log(err.message); // ReferenceError: y is not defined
SyntaxError occurs when we forget to close bracket or add extra brackets into code. Look at the below example:
try {
let x = function() {
return 'Hello World!';
});
} catch (err) {
console.log(err);
}
The above code will generate error: SyntaxError: Unexpected token ')'
Now let's look an example of system error. We have used fs module to read the file which doesn't exists.
const fs = require('fs');
fs.readFile('/file/not/exist', function(err, data) {
if (err) {
console.log(err.message);
return;
}
console.log(data);
});
The above code will generate error: [Error: ENOENT: no such file or directory, open '/file/not/exist']
Note that we can't use try...catch
function in asynchronous APIs. This is because before callback function is called, the surrounding code, including the try…catch block, will have already exited.
Generating error
You can also create a new Error object and sets the error.message property to the provided text message.
For example:
const err = new Error('This is custom error');
console.log(err); // This is custom error
This will throw unknown error. I hope it will help you.