- Using try catch finally in Node.js [Best Practices]
- An in-depth explanation of try catch finally in Node.js
- Lab setup to explore try catch finally in Node.js
- Synchronous code examples
- Example~1: Add two numbers
- Example~2: Read a file that does not exist
- Asynchronous code examples
- Example~3: Misspell part of an API URL
- Conclusion
- JavaScript Errors
- Errors Will Happen!
- Example
- JavaScript try and catch
- JavaScript Throws Errors
- The throw Statement
- Input Validation Example
- HTML Validation
- The finally Statement
- Syntax
- Example
- The Error Object
- Error Object Properties
- Error Name Values
- Eval Error
- Range Error
- Example
- Reference Error
- Example
- Syntax Error
- Example
- Type Error
- Example
- URI (Uniform Resource Identifier) Error
- Example
- Non-Standard Error Object Properties
- Complete Error Reference
Using try catch finally in Node.js [Best Practices]
try catch finally in node.js handle runtime errors. Here is the syntax for usage:
Runtime errors occur during the execution of the program. Unlike the syntax errors that a typical code editor can easily catch, runtime errors could go unnoticed until the program throws them during its execution.
Such errors are called exceptions. And writing code that handles them is called exception handling. This tutorial simplifies exception handling using try catch finally in Node.js.
An in-depth explanation of try catch finally in Node.js
We handle runtime errors by putting the main code in the try block and grabbing the errors in the catch block. The code execution in the try block halts until the exception is handled in the catch block. Contrarily, a finally block runs whether an exception is caught (and handled) or not.
Here is more to know when using try catch finally in Node.js:
1). The try block generates an error object, then throws it to the nearest catch block. The catch block then accepts the error object through the given parameter. As a result, we can print the entire error object or one of its properties, like the message .
2). try catch finally are blocks.
We cannot use them in expressions as you would in other control flow mechanisms like if/else. For example, we could drop the curly braces for a (one-line) condition in the if/else control flow.
const input = "Hello" // a block if (input === "Hello") < console.log("Correct") >else < console.log("The input is not 'Hello'") >// an expression if (input === "Hello") console.log("Correct") else console.log("The input is not 'Hello'")
Contrarily, we cannot run the try catch finally in Node.js as expressions.
const input = "Hello" // Correct try < throw new Error("Something went wrong") >catch (error) < console.log("Error: ", error) >finally < console.log(input, "my friend") >// Wrong try throw new Error("Something went wrong") catch (error) console.log("Error: ", error) finally console.log(input, "my friend")
3). The try block is compulsory and must come before the (optional) catch and finally blocks.
const input = "Hello" // without finally try < throw new Error("Something went wrong") >catch (error) < console.log("Error: ", error) >// without catch try < if (input === "Hello") console.log("Hello my friend") >finally
Now that you understand how to use try catch finally in Node.js, let me show you to apply the concepts practically. First, let’s set up a lab environment.
Lab setup to explore try catch finally in Node.js
Create the following project structure.
exceptionHandling ├── sync.js └── async.js
In the examples section, we will run try catch finally in Node.js in synchronous and asynchronous code in the sync.js and async.js files, respectively.
I am creating the folder structure on Linux and opening it with Visual Studio Code.
mkdir exceptionHandling && cd exceptionHandling touch sync.js async.js code .
Now let’s dive into practical examples of try catch finally in Node.js.
Synchronous code examples
Example~1: Add two numbers
// in sync.js const addTwoNumbers = (num1, num2) => < try < if (typeof num1 !== "number" || typeof num2 !== "number") throw new Error("Can't add a number to another data type!") else console.log(`$+ $ = $`) > catch (error) < console.log(error.message) >finally < console.log(". I like to add numbers.\n") >> addTwoNumbers(3, "2") addTwoNumbers(3, 5)
The try block checks whether both inputs are numbers and throw s a custom error object if either input is not a number. Otherwise, it prints the sum.
The catch block receives the thrown error object and prints its message property.
The finally block prints a statement whether an error is caught or not.
Now run the script file with the node command.
$ node sync.js Cant't add a number to another data type! . I like to add numbers. 3 + 5 = 8 . I like to add numbers.
Example~2: Read a file that does not exist
// in sync.js const fs = require("fs") try < const output = fs.readFileSync('file.txt', 'utf-8') console.log(output) >catch < console.log("There was an error reading the file.") >finally
We import the fs module. Using the module’s readFileSync() method, we attempt to read a file called file.txt in the try block. If we successfully read the file, we print its content on the console output.
Otherwise, the produced error prevents the program from reaching the console.log(output) line. Instead, it throws an error, leading to the printing of the message in the catch block. The finally block prints the message try catch finally in Node.js helps regardless.
$ node sync.js There was an error reading the file. try catch finally in Node.js helps
Asynchronous code examples
Example~3: Misspell part of an API URL
// in async.js const getUsers = async () => < try < const res = await fetch("https://reqres.in/epi/users?page=2") if (res.status !== 200) throw new Error("Error: Something is wrong with the URL!") const data = await res.json() console.log(data) >catch (error) < console.log(error.message) >finally < console.log("finally, try catch finally in Node.js async-await code") >> getUsers()
In the try block, we attempt to fetch users from the API after misspelling api for epi. We throw a custom error if the request is not OK. Otherwise, we store the returned data in the data variable, then console-log the variable.
We throw the resulting error object to the catch block, where we print the object’s message property.
Whether the API call succeeds or fails, we console-log the message in the finally block. Lastly, we run the getUsers() function.
Run the script file on the terminal with the node command to see the output.
$ node async.js (node:3884) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time (Use `node --trace-warnings . ` to show where the warning was created) Error: Something is wrong with the URL! finally, try catch finally in Node.js async-await code
Conclusion
Knowing how to use the try catch finally in Node.js effectively helps in exception handling. The try block handles the main code. The catch block receives an error object from the try block(s) and handles it. Lastly, the code in the finally block runs whether an exception is handled or not.
JavaScript Errors
The try statement defines a code block to run (to try).
The catch statement defines a code block to handle any error.
The finally statement defines a code block to run regardless of the result.
The throw statement defines a custom error.
Errors Will Happen!
When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.
Example
In this example we misspelled «alert» as «adddlert» to deliberately produce an error:
try adddlert(«Welcome guest!»);
>
catch(err) document.getElementById(«demo»).innerHTML = err.message;
>
JavaScript catches adddlert as an error, and executes the catch code to handle it.
JavaScript try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs:
JavaScript Throws Errors
When an error occurs, JavaScript will normally stop and generate an error message.
The technical term for this is: JavaScript will throw an exception (throw an error).
JavaScript will actually create an Error object with two properties: name and message.
The throw Statement
The throw statement allows you to create a custom error.
Technically you can throw an exception (throw an error).
The exception can be a JavaScript String , a Number , a Boolean or an Object :
If you use throw together with try and catch , you can control program flow and generate custom error messages.
Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed:
Please input a number between 5 and 10:
function myFunction() const message = document.getElementById(«p01»);
message.innerHTML = «»;
let x = document.getElementById(«demo»).value;
try <
if(x.trim() == «») throw «empty»;
if(isNaN(x)) throw «not a number»;
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw «too high»;
>
catch(err) message.innerHTML = «Input is » + err;
>
>
HTML Validation
The code above is just an example.
Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:
You can read more about forms validation in a later chapter of this tutorial.
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
Syntax
try <
Block of code to try
>
catch(err) <
Block of code to handle errors
>
finally <
Block of code to be executed regardless of the try / catch result
>
Example
function myFunction() <
const message = document.getElementById(«p01»);
message.innerHTML = «»;
let x = document.getElementById(«demo»).value;
try <
if(x.trim() == «») throw «is empty»;
if(isNaN(x)) throw «is not a number»;
x = Number(x);
if(x > 10) throw «is too high»;
if(x < 5) throw "is too low";
>
catch(err) <
message.innerHTML = «Error: » + err + «.»;
>
finally <
document.getElementById(«demo»).value = «»;
>
>
The Error Object
JavaScript has a built in error object that provides error information when an error occurs.
The error object provides two useful properties: name and message.
Error Object Properties
Property | Description |
---|---|
name | Sets or returns an error name |
message | Sets or returns an error message (a string) |
Error Name Values
Six different values can be returned by the error name property:
Error Name | Description |
---|---|
EvalError | An error has occurred in the eval() function |
RangeError | A number «out of range» has occurred |
ReferenceError | An illegal reference has occurred |
SyntaxError | A syntax error has occurred |
TypeError | A type error has occurred |
URIError | An error in encodeURI() has occurred |
The six different values are described below.
Eval Error
An EvalError indicates an error in the eval() function.
Newer versions of JavaScript do not throw EvalError. Use SyntaxError instead.
Range Error
A RangeError is thrown if you use a number that is outside the range of legal values.
For example: You cannot set the number of significant digits of a number to 500.
Example
let num = 1;
try num.toPrecision(500); // A number cannot have 500 significant digits
>
catch(err) document.getElementById(«demo»).innerHTML = err.name;
>
Reference Error
A ReferenceError is thrown if you use (reference) a variable that has not been declared:
Example
let x = 5;
try x = y + 1; // y cannot be used (referenced)
>
catch(err) document.getElementById(«demo»).innerHTML = err.name;
>
Syntax Error
A SyntaxError is thrown if you try to evaluate code with a syntax error.
Example
try <
eval(«alert(‘Hello)»); // Missing ‘ will produce an error
>
catch(err) <
document.getElementById(«demo»).innerHTML = err.name;
>
Type Error
A TypeError is thrown if you use a value that is outside the range of expected types:
Example
let num = 1;
try num.toUpperCase(); // You cannot convert a number to upper case
>
catch(err) document.getElementById(«demo»).innerHTML = err.name;
>
URI (Uniform Resource Identifier) Error
A URIError is thrown if you use illegal characters in a URI function:
Example
try <
decodeURI(«%%%»); // You cannot URI decode percent signs
>
catch(err) <
document.getElementById(«demo»).innerHTML = err.name;
>
Non-Standard Error Object Properties
Mozilla and Microsoft define some non-standard error object properties:
fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)
Do not use these properties in public web sites. They will not work in all browsers.
Complete Error Reference
For a complete reference of the Error object, go to our Complete JavaScript Error Reference.