Exceptions can be suppressed in Chrome and Firefox but none of the approaches work in IE
window.addEventListener("error", function errorHandler(event) {
console.log("exception should be suppressed and not shown in the console");
event.preventDefault();
});
throw "suppress me";
and
window.onerror = function errorHandler() {
console.log("exception should be suppressed and not shown in the console");
return true;
};
throw "suppress me";
You can play with them
https://jsfiddle.net/9uj4xm3g/4/
https://jsfiddle.net/gv0pvy3b/3/
Any ideas?
UPD:
I forgot to clarify what I mean by suppressing. I would like to be able to hide SCRIPT5022 message completely by marking an error as handled.
According to https://msdn.microsoft.com/en-us/library/cc197053.aspx
To suppress the default Windows Internet Explorer error message for
the window event, set the returnValue property of the event object to
true or simply return true in Microsoft JScript.
But as you see this doesn't help with errors logged to the console
The problem here is how you're throwing the exception.
You should be doing the following:
throw new Error("my error");
Here's a reference: https://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
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 need to run third party JS to scan jserrors. I am running the following in chrome's console
window.onerror = function(errorMsg, url, lineNumber) {
alert(errorMsg);
}
throw new Error('foo');
I expect both the console to inform me of the error and a alert to pop up displaying the error message. The alert is never fired, and I assume the event is not being fired. why not?
The Chrome Developer Console won't call the user-defined error event listener if the error is thrown immediately (according to this answer by Paul S.).
Throwing the error "just in time":
> window.onerror = function () {console.log('error!');};
function () {console.log('error!');}
> throw new Error();
Error
Throwing the error deferred:
> window.setTimeout(function() {throw new Error()}, 0);
xxxx
error!
Uncaught Error
(xxxx is the specific return value of setTimeout())
Here is the original code snippet which led me to the point that the Chrome Dev Console changes the internal behaviour somehow:
// #btn is a simple button
document.getElementById("btn").addEventListener("click", function () {
var script = document.createElement("script");
script.innerHTML = "window.onerror=function(){alert('An error occurred!');};throw new Error('42');";
document.head.appendChild(script);
});
This code is to be executed in a normal HTML file.
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.
I have noticed that even with "show stack trace with errors" enabled from the drop down, only errors that occur seem to have traces, but when I do: throw new Error('foo'); I do not see any stack trace for it even though it seems to appear in the console exactly the same way as other errors that occur such as iDoNotExist().
Is there something I am missing?
It also seems that I get the stack trace for calling console.error('foo');. Odd.
It should be noted that stack traces do occur on Webkit Inspector and Opera when doing throw new Error('foo');.
For others landing here :
The issue for me was showStackTrace is set to false by default for Firebug.
Here's how to enable it :
Goto about:config in Firefox
Change the value of the preference extensions.firebug.showStackTrace from false to true (Double-click toggles the value).
I tested this code in Firebug 1.7.1b2 (FF: 4.0.1, on win7) and it shows me stack trace:
function a(){
throw new Error('s');
};
function b(){
a()
}
b();
Have you tried:
var err = new Error();
err.name = 'My custom error';
err.message = 'foo';
throw(err);
Or even (doesn't always work):
throw 'foo';
throw('foo');
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.