As a C# developer I'm used to the following style of exception handling:
try
{
throw SomeException("hahahaha!");
}
catch (Exception ex)
{
Log(ex.ToString());
}
Output
------
SomeNamespace.SomeException: hahahaha!
at ConsoleApplication1.Main() in ConsoleApplication1\Program.cs:line 27
Its really simple, and yet tells me everything I need to know about what the exception was and where it was.
How do I achieve the equivalent thing in JavaScript where the exception object itself might just be a string. I really want to be able to know the exact line of code where the exception happened, however the following code doesn't log anything useful at all:
try
{
var WshShell = new ActiveXObject("WScript.Shell");
return WshShell.RegRead("HKEY_LOCAL_MACHINE\\Some\\Invalid\\Location");
}
catch (ex)
{
Log("Caught exception: " + ex);
}
Output
------
Caught exception: [object Error]
EDIT (again): Just to clarify, this is for internal application that makes heavy use of JavaScript. I'm after a way of extracting useful information from JavaScript errors that may be caught in the production system - I already have a logging mechanism, just want a way of getting a sensible string to log.
You don't specify if you are working in the browser or the server. If it's the former, there is a new console.error method and e.stack property:
try {
// do some crazy stuff
} catch (e) {
console.error(e, e.stack);
}
Please keep in mind that error will work on Firefox and Chrome, but it's not standard. A quick example that will downgrade to console.log and log e if there is no e.stack:
try {
// do some crazy stuff
} catch (e) {
(console.error || console.log).call(console, e.stack || e);
}
As Eldar points out, you can use e.message to get the message of the exception. However, in Chrome, Firefox and IE10+, you can also get the stack trace using e.stack. The stack trace will include the file and line number of the exception.
So to assemble a string with exception info, you would write something like this:
var exmsg = "";
if (e.message) {
exmsg += e.message;
}
if (e.stack) {
exmsg += ' | stack: ' + e.stack;
}
Note that you will only get a stack trace if
the exception was thrown by the browser (such as in response to a
syntax error);
the exception object is an Error object or has the Error object as its prototype.
So just throwing a string (throw 'Exception!!') won't give you a stack trace.
To take this a bit further, to catch all uncaught exceptions, you would use a window.onerror handler (similar to .Net Application_Error handler in global.asax). The drawback of this used to be (and mostly still is) that this wouldn't give you access to the actual exception object, so you couldn't get the stack trace. You'd only get the message, url and line number.
Recently, the standard has been extended to give you the column (great for minified files) and the exception object as well:
http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#errorevent
Right now (April 2014), only Chrome 32 implements all this. IE10+ gives you the column but not the exception object. Firefox 28 still only gives you message, url and line number. Hopefully, this will improve soon. I've written about this for the JSNLog project, at:
http://jsnlog.com/Documentation/GetStartedLogging/ExceptionLogging
(disclaimer: I am the author of JSNLog and jsnlog.com)
Secondly, the .Net Exception object supports inner exceptions. It also has a Data property so you can attach key value pairs with for example variable values. I sort of missed that in JavaScript Error object, so I created my own Exception object, also as part of the JSNLog project. It is in the jsnlog.js file in the jsnlog.js Github project (https://github.com/mperdeck/jsnlog.js).
Description is at:
http://jsnlog.com/Documentation/JSNLogJs/Exception
Finally a shameless plug - the JSNLog project I'm working on lets you insert loggers in your JavaScript, and automatically inserts the log messages in your existing server side log. So to log JavaScript exceptions with their stack traces to your server side log, you only need to write:
try {
...
} catch (e) {
JL().fatalException("something went wrong!", e);
}
You can use almost in the same manner ie.
try
{
throw new Error("hahahaha!");
}
catch (e)
{
alert(e.message)
}
But if you want to get line number and filename where error is thrown i suppose there is no crossbrowser solution. Message and name are the only standart properties of Error object. In mozilla you have also lineNumber and fileName properties.
I'm not sure whether or not it is cross browser or if it's what you are looking for, but I suggest you try:
window.onerror = function (err, file, line) {
logError('The following error occurred: ' +
err + '\nIn file: ' + file + '\nOn line: ' + line);
return true;
}
I had a similar problem.
Using console.table(error); worked well for me.
It displays information in a table, and also lets me expand/collapse to see more details.
It is almost identical, see the manual: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Exception_Handling_Statements/try...catch_Statement
You can use logging tools like Yahoo! UI Library - Logger to log the errors/informative messages.
I wrote a handy function for it
const logError = (e: any) => {
if (console.error) console.error(e, e.stack);
else console.log(e)
}
The modern best practice (as I understand it) is to log the error as a separate argument to console.error (or console.log, console.warn, etc...)
try {
maybeThrows()
} catch (e) {
console.error('it threw', e);
}
Trying out this approach in practice:
try {
throw Error('err') // Error object
} catch (e) {
console.error('it threw', e); // it threw Error: err
}
try {
throw 'up' // not an error object
} catch (e) {
console.error('it threw', e); // it threw up
}
I ran the above in Chrome, and Node v16. Note that node did not include a stack trace for throw 'up', but did for the proper error. Chrome included the stack for both.
Related
When a Uncaught Exception is thrown in some website or web application, an error appears in the Develper tools in each browser
In Electron for instance, if an uncaught exception, the developer can set a listener and do whatever I want with the error message:
process.on('uncaughtException', function (error) {
// Handle the error
}
So, I wonder if there is an easy way to do the same in JavaScript. This could be useful in order to record and store common errors when the users are working, or in order to show what's happening to the user, who can send feedback to the developers.
Something like this could be shown instead
Sometimes, if an error occurs the app become in a unstable state where everything is frozen, and the user do not know why. I think informing about the error is important.
I found this Error JavaScript object. It can be manually thrown, but that can be used only when try and catch are used, and not for the uncaught exceptions, where the developer made some mistakes.
You can handle it as an event listener on window object.
window.onunhandledrejection = event => {
console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
};
window.onerror = function(message, source, lineNumber, colno, error) {
console.warn(`UNHANDLED ERROR: ${error.stack}`);
};
Or also like this:
window.addEventListener('error', function(event) { ... })
You can read more about the unhandledrejection event on the MDN web docs here and the onerror event on the docs here
try {
// YOUR CODE GOES HERE
} catch (e) {
if ( e instanceof CustomExceptionError ) {
// ...
} else if ( e instanceof OtherExceptionError ) {
// ...
} else {
// ...
}
//OR CALL THE ALERT BOX OR ANY OTHER UI CHANGE
}
I am working on a JavaScript project and am struggling to pass the final unit test, which essentially checks if my function throws an error if the given input is invalid. For some background, it is a function which deals with user permissions, and can check if certain permissions can be granted or denied, given certain prerequisites.
I can pass all the tests with regards to the output of the functions, but am having trouble with error handling. I am being told that I am not throwing an error, despite checking myself multiple times that an error is indeed being thrown. I'll attach images to illustrate the issue as best as possible.
First, the error object which I am trying to throw is defined below:
function InvalidBasePermissionsError() {
this.name = 'InvalidBasePermissionsError';
this.message = "Invalid Base Permissions";
this.stack = Error().stack;
}
InvalidBasePermissionsError.prototype = Object.create(Error.prototype);
My function which is failing the error-throwing test is as follows:
PermissionDependencyResolver.prototype.canDeny = function (existing, permToDeny) {
try {
if (!pdr.checkValid(existing)) {
throw new InvalidBasePermissionsError;
}
else {
var tempArr = existing
var required = [];
for (var i = 0; i < tempArr.length; i++) {
var current_dependency = this.adjList[existing[i]];
required.push.apply(required, current_dependency)
};
if (required.includes(permToDeny)) {
return false;
} else {
return true;
}
}
}
catch (e) {
console.log(e.message)
}
};
The strange thing is that when I console log the function as follows:
pdr.canDeny(['create', "delete"], 'audit')
I get the correct string "Invalid Base Permissions" printed to the console, see image1. What is even more strange is that when I run the tests, I can see this same error message being logged directly above the "failed test" message, which seems contradictory, see image 2. Is it possible that Mocha (the test framework) isn't picking up on my error handling; or have I made a mistake in my function and am not throwing the error appropriately?
The tests in question are as follows:
it('throws an exception when validating permissions if existing permissions are invalid', function(){
pdr = new PermissionDependencyResolver(complexPermissionDependencies)
expect(function () { pdr.canGrant(['edit', 'create'], 'alter_tags') }).toThrowError("Invalid Base Permissions")
expect(function () { pdr.canGrant(['view', 'delete'], 'alter_tags') }).toThrowError("Invalid Base Permissions")
expect(function () { pdr.canDeny(['create', 'delete'], 'audit') }).toThrowError("Invalid Base Permissions")
})
Is it possible that Mocha (the test framework) isn't picking up on my error handling; or have I made a mistake in my function and am not throwing the error appropriately?
Again, when I manually console log each of the cases being tested, they all throw the error message "Invalid Base Permissions" as expected. For some reason, however, the tests are telling me that nothing is being thrown.
Any ideas as to what might be causing this would be a massive help, as I'm at a loss as to what the source of the error is. Is it Mocha, JS, my try/catch syntax or some other issue. Any help is really appreciated.
Thanks!
Managed to find an answer after extensive digging around, will post in case anybody else has similar issues in future. Correct answer here: http://www.itjavascript.com/why-won-39-t-mocha-recognise-my-error-ask-question/
Basically, I was handling the error before it reached the test, so removing the try/catch statements solved the problem. Silly in hindsight but apparently you need to be very explicit with Mocha. Hopefully this'll prove useful for somebody in the future!
is there a way to send the line and file a console function has been called?
i got an app with many console log and console error in it. thats a good thing for me, the problem is i need to know from where they came from.
i tried override console.error and add console.trace inside but that just created a recursive call to console error(i guess they both triggered by process strerr)
here is what i have tried
const tempConsoleError = console.error.bind(console);
console.error = function (err) {
console.log('i am in error')
tempConsoleError(err);
console.trace()
};
console.error('error string ')
ended up writing a packages to do it. is uses the "stack-trace" and node global
console-from
To make debugging easier, I'm capturing all of the console logs in Chrome so that users who submit a feedback entry will also submit all of the logs to our server. When someone encounters a problem in production, I can first and foremost get them back to work so that I can then sit down and more thoroughly go through all of the logs to determine the root cause of whatever issue the user encountered in production.
The technique I use to capture the logs involves overriding console.log so that all text entered in the first argument gets stored in an array while simultaneously invoking the legacy function so that I can still see the logs in the console too.
The problem is when there's the occasional uncaught exception. These aren't included in the uploaded logs, so it's not always clear what caused the problem. So I tried overriding ReferenceError by writing a JavaScript function that takes a function as an argument, then returns a new function that does stuff with it, like storing data in a variable, and then invoking the legacy function as the last step:
function overrideException(legacyFn) {
/** arguments for original fn **/
return function() {
var args = [];
args[0] = arguments[0];
// pass in as arguments to original function and store result to
// prove we overrode the ReferenceError
output = ">> " + legacyFn.apply(this, args).stack;
return legacyFn.apply(this, arguments);
}
}
To test the overrideException function, I ran the following code on the console:
ReferenceError = overrideException(ReferenceError);
Afterwards, I tested the returned function, the new ReferenceError, by manually throwing a ReferenceError:
throw new ReferenceError("YES!! IT WORKS! HAHAHA!");
The resulting output on the console is:
ReferenceError: YES!! IT WORKS! HAHAHA!
And checking the global variable output from the overrideException function shows that it did indeed run:
output
">> ReferenceError: YES!! IT WORKS! HAHAHA!
at ReferenceError (<anonymous>)
at new <anonymous> (<anonymous>:18:35)
at <anonymous>:2:7
at Object.InjectedScript._evaluateOn (<anonymous>:562:39)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:521:52)
at Object.InjectedScript.evaluate (<anonymous>:440:21)"
Now, here's where things start to fall apart. In our code, we're not going to know when an uncaught exception occurs, so I tested it by attempting to run a function that doesn't exist:
ttt();
Which results in:
ReferenceError: ttt is not defined
However, unlike the case where we explicitly throw an error, in this case, the function doesn't fire, and we're left with only the legacy functionality. The contents of the variable output is the same as in the first test.
So the question seems to be this: How do we override the ReferenceError functionality that the JavaScript engine uses to throw errors so that it's the same one we use when we throw a ReferenceError?
Keep in mind that my problem is limited only to Chrome at this time; I'm building a Chrome Packaged app.
I have done quite a bit of research for the same reason: I wanted to log errors and report them.
"Overriding" a native type (whether ReferenceError, String, or Array) is not possible.
Chrome binds these before any Javascript is run, so redefining window.ReferenceError has no effect.
You can extend ReferenceError with something like ReferenceError.prototype.extension = function() { return 0; }, or even override toString (for consistency, try it on the page, not the Dev Tools).
That doesn't help you much.
But not to worry....
(1) Use window.onerror to get file name, 1-indexed line number, and 0-indexed position of uncaught errors, as well as the error itself.
var errorData = [];
onerror = function(message, file, line, position, error) {
errorData.push({message:message, file:file, line:line, position:position, error:error});
};
See the fiddle for an example. Since the OP was Chrome-specific, this has only been tested to work in Chrome.
(2) Because of improvements to (1), this is no longer necessary, but I leave this second technique here for completeness, and since onerror is not guaranteed to work for all errors on all browsers. You will also sometimes see the following:
var errors = [];
function protectedFunction(f) {
return function() {
try {
f.apply(this, arguments);
} catch(e) {
errors.push(e);
throw e;
}
};
}
setTimeout = protectedFunction(setTimeout);
setInterval = protectedFunction(setInterval);
etc...
FYI, all this is very similar to what has been done in the Google Closure Compiler library, in goog.debug, created during Gmail development with the intent of doing exactly this. Of particular interest is goog.debug.ErrorHandler and goog.debug.ErrorReporter.
I can't find a way to catch the error message under firefox:
window.addEventListener("error", handleException, false);
...
function handleException(e) {
alert(e);
return false;
}
...
<script>
throw new Error('sdasd');
</script>
This enters very well the handleException method however the e parameter is an error event under firefox and I don't know how to get the associated message.
In chrome for instance, I get either the message through e.message because after the error bubbles up to not being caught, there's an automatic error fired at window level (See this fiddle: the final error is "Uncaught") that contains the original error that I raised manually.
So to have the same behaviour under firefox (if you run the fiddle under firefox you'll see that the message is "undefined") I found a workaround consisting in encapsulating an error raising function to setup a manual "last error" architecture:
function err(I_sText) {
g_lastManualError = new Error(I_sText);
throw g_lastManualError; //this variable is global so I can get the message from anywhere
}
So instead of doing throw new Error(..) I only call err(..). That works, at least for user defined exceptions, which are my biggest concern. In my handler handleException I'm consulting the global variable.
Do you know how I could do otherwise? I'm not happy with this solution.
Thank you,
S.
I modified your code a little as a demo:
function handleException(e) {
console.log(e);
alert(e);
return false;
}
window.addEventListener("error", handleException, false);
try {
throw new Error('sdasd');
}
catch (e) {
console.log(e)
}
console.log('after exception 1');
throw new Error('foo');
console.log('after exception 2');
Running this code (in Firebug) showed me this:
Error: sdasd
[Break On This Error]
Filtered chrome url chrome://firebug/content/console/commandLineExposed.js
comman...osed.js (line 175)
<System>
after exception 1
"Error: foo ` throw new Error('foo');` #14"
If you're trying to catch an error, use try {...} catch { ...}. It looks like you're just binding to an error event, so the exception you're throwing will still propagate up to window and tell the JS engine to halt. Run this code in Chrome, you'll see that you never see "after exception 2", but you will see "after exception 1".
The purpose of exceptions (created by throw) is to stop code execution unless there's code made to handle that particular exception. You can see an example on the MDN page for try-catch
Edit: it just occurred to me that you might be trying to catch a jQuery error event. If this is the case, your event binding is correct but you shouldn't be testing it with throw
Edit 2: I should've noticed this sooner, but you're trying to listen for a DOM error event with window.addEventListener. Error events will not break execution. Exceptions do.
Replace your code throw new Error('sdasd'); with this code:
var customEvent = new CustomEvent('error')
window.dispatchEvent(customEvent);
That should solve your problem. I used the MDN page on custom events as a reference.