How to log exceptions in Javascript

Published on

At work we use a tool for error logging and monitoring of our web applications. This tool captures and logs any errors automatically. But, we sometimes do some manual logging, which looks something like this:

try {
	// code that throws an exception
} catch (e) {
	logMessage(`exception - ${e.toString()}`);
}

The problem with this code is that the Exception e could be anything. We had assumed that it would be an Error object, but looking at the logs we found out that it could be null / undefined or things like [object Event].

With this information, we know that we should handle these cases:

So we can use a helper function to stringify the exception:

function stringifyException(exception) {
	if (!exception) {
		return 'unknown exception';
	}
	// if it's an ErrorEvent
	if (exception instanceof ErrorEvent && exception.error) {
		return exception.error.toString();
	}
	// or another type of Event
	if (exception instanceof Event) {
		return `Event: ${exception.type}`;
	}
	// otherwise we can use toString()
	// which works well for Errors and primitive objects
	return exception.toString();
}

In the end, we were able to handle all types of exceptions, even if we didn't get much information about some of them (null, undefined and events). But, by using the helper we catch the exceptions correctly and we can be more confident in our code.