The meaning of life is to explore the world

Error.message in try catch block in JS

Posted on By Jason Liu

Error class in JS has the message property.
We should try to throw Error object instead of other random stuff like boolean, string etc.
This includes errors thrown from Promise.reject()
E.g. In the codes below, test(f1) works while test(f2) does not.

async function f1() {
	return new Promise((resolve, reject) => {
		reject(new Error('f1'));
	});
}

async function f2() {
	return new Promise((resolve, reject) => {
		reject('f2');
	});
}

async function test(f) {
	try {
		await f();
	} catch (error) {
		console.log('Err found: ' + error.message);
	}
}

test(f1);
test(f2);