Obviously occuring errors is normal in any application. When error occurs, Node.js generates four categories of errors:
<EvalError>
, <SyntaxError>
, <RangeError>
, <ReferenceError>
, <TypeError>
, and <URIError>
.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.
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.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
PHP Uploading Multiple files using Dropzone
In this article, we will share with you...How to Preview an Image Before it is Uploaded Using jQuery
Use the JS readAsDataURL() Method You...How to Generate Captcha Code in Laravel
Captcha is the security to stop brute fo...Increment and Decrement Column Value in Laravel
In this article we will share with you h...Laravel 8 Vue JS CRUD Operation Single Page Application
Throughout this Laravel Vue js CRUD exam...