Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to Catch an Error from External Library and Store it in...

How to Catch an Error from External Library and Store it in a String in JavaScript ?

When using an external library in our code, we may encounter errors. It is essential to catch these errors and handle them gracefully. In some cases, we may want to store the error message in a string for further processing or display it to the user.

In this article, we will learn how to catch an error from an external library and store it in a string using various approaches. Storing the error message in a string provides a convenient way to handle and report the error. By storing the error message in a string, you can perform various operations with the error message, such as logging it, displaying it to the user, or sending it to a logging service.

Let’s consider an example where we are using the MathJS library to perform mathematical calculations. Suppose we want to calculate the square root of a negative number. MathJS will throw an error in such cases, and we need to catch that error and store the error message in a string.

 

Example:

Javascript




const math = require('mathjs');
let num = -9;
let result;
try {
    result = math.sqrt(num);
} catch (error) {
    console.log(error);
}


Output(Error):

TypeError: Cannot convert undefined or null to object
at f (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:3565:53)
at l._compile (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:11054:25)
at l.compile (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:10950:10)
at r.parse (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:7647:18)
at u.parse (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:8763:22)
at l.parse (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:11026:20)
at Function.parse (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:10937:12)
at t.parse (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:23821:14)
at Object.parse (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:23905:14)
at Object.sqrt (https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.js:3055:22) 

Approach 1: To catch the error and store it in a string, we can use the try-catch block and stack property that converts the error message to a String.

Example: In the below code, we have added a variable called errorMessage and assigned it the error message if an error occurs while calculating the square root. We can then use this string to display the error message to the user or log it for further processing.

Javascript




const fs = require('fs');
  
try {
    const data = fs.readFileSync('path/to/file.txt');
    console.log('Data:', data);
} catch (error) {
    const errorMessage = error.stack.toString();
  
    console.error('Error:', errorMessage);
}


Output:

Error: Error: ENOENT: no such file or directory, open 'path/to/file.txt'

Approach 2: To catch the error and store it in a string, we can use the try-catch block and inspect() method of the util library that converts the error message to a String.

Example: This code example shows how to catch an error from an external library (in this case, the fs module in Node.js) and store it in a string using the util library.

Javascript




const fs = require('fs');
const util = require("util")
  
try {
    const data = fs.readFileSync('path/to/file1.txt');
} catch (error) {
    const errorMessage = util.inspect(error);
    console.error(errorMessage);
}


Output:

Error: ENOENT: no such file or directory, open 'path/to/file1.txt'

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments