Convert an Error Object to a String in JavaScript


Borislav Hadzhiev

Last updated: Dec 24, 2021


Check out my new book

Convert an Error Object to a String in JavaScript #

To convert an error object to a string, access the message property on the object, e.g. err.message. The message property is a human-readable description of why the error occurred.

const err = new Error('Something went wrong'); console.log(err.message); // 👉️ "Something went wrong"

When an error is created using the Error() constructor, we are able to access the message property on the error to get a human-readable string of the reason the error occurred.

In some rare scenarios third party packages throw errors without using the native Error() constructor or extending from it.

The best practice is to always throw an error using the error constructor or extend it if you need added functionality.

throw new Error('Something went wrong'); Promise.reject(new Error('Something went wrong'));

Even when rejecting a promise, you can pass an error to the reject() method.

If you have to deal with strange implementations of an error from third party packages, you should check if the error value is an object and has the message property to avoid accessing a non-existent property.

const err = null; if (typeof err === 'object' && err !== null && 'message' in err) { const message = err.message; console.log(message); }

Our if condition uses the logical AND (&&) operator, so for the if block to run, all of the conditions have to be met.

We first check if the err variable stores a value with a type of object because errors have a type of object.

Then we check if the variable is not equal to null. Unfortunately, if you check the type of null - console.log(typeof null), you will get an "object" value back, so we have to make sure the value is not null.

The last thing we check for is that the object contains the message property.

Then we know we can safely access the message property on the object.

If that doesn't work, as a last resort, you can try to access the toString() method on the error object.

Some third party packages throw error objects that implement the toString() method.

const err = null; if (typeof err === 'object' && err !== null && 'toString' in err) { const message = err.toString(); console.log(message); }

If that doesn't work either, you have to console.log the error object and investigate what properties and methods it implements.

Use the search field on my Home Page to filter through my more than 3,000 articles.