How to Catch an Error from External Library and Store it in a String in JavaScript ?
Last Updated :
28 Apr, 2025
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'
Similar Reads
How to throw an error in an async generator function in JavaScript ? In this article, we will try to understand how to throw an error in a synchronous (abbreviated as "async") generator function in JavaScript with the help of theoretical as well as coding examples. Let us first have a look into the following section which will show us the syntax for declaring an asyn
2 min read
How to append new information and rethrowing errors in nested functions in JavaScript ? In this article, we will see how we may append new information and rethrow errors in nested functions in JavaScript with the help of certain theoretical explanations & understand them through the illustrations. This article is divided into 2 sections, i.e. in the 1st section, we'll understand ho
5 min read
How to catch all JavaScript errors and send them to server ? Today there are a large number of Web APIs available. One of which is GlobalEventHandlers, an OnErrorEventHandler to be called when the error is raised. The onerror property of the GlobalEventHandlers is an EventHandler that processes error events. This is great for catching exceptions that never oc
2 min read
How to Catch JSON Parse Error in JavaScript ? JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However,
1 min read
Losing a Backtrace in the catch block in JavaScript In this article, we will see that "JavaScript is losing a backtrace in the catch block". A backtrace means, losing something because of your past events. A stack is maintained, by JavaScript to keep track of the invoked functions, which are not returned yet. A try-catch block was introduced by JavaS
4 min read