How to catch *all* errors and exceptions with Sentry? - javascript

Out of 24 errors that appear in the console of my page in Chrome, Sentry only records one.
I have followed the documentation and ensured that Sentry is loaded and initialized in the <head> of the page, after jQuery, but before our CMS vendor code and custom bundles:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://browser.sentry-cdn.com/5.8.0/bundle.min.js" crossorigin="anonymous"</script>
<script>
Sentry.init({
dsn: "https://...#.../..."
});
</script>
<script src="..."></script>
I have also patched Sentry as described here to copy console.error() with Sentry.captureMessage(), so that I am now seeing three messages in Sentry.
But I am still struggling with three types of errors:
Uncaught TypeError
error in a JS file coming from our CMS
some very particular <img> srcset errors
As regards the srcset errors: I have already added onerror handlers to the images. They are called in some cases, but not in this particular case (the srcset attribute has a space in the filename which violates the syntax); admittedly, this problem should rather be reported to the Chrome dev team than fixed in Sentry.
I have tried to capture these errors myself and redirect them manually to Sentry, but none of the following listeners even catches them in Chrome (sorry for the .join(), just test code, I didn't beautify it):
window.onerror = function (errorMsg, url, lineNumber) {
alert(["window.onerror", errorMsg, url, lineNumber].join());
return true;
};
window.addEventListener("unhandledrejection", function (e) {
alert(["window: Unhandled Rejection", e.reason.message].join());
});
window.addEventListener("rejectionhandled", function (e) {
alert(["window: rejectionhandled", e.reason.message].join());
});
window.addEventListener("error", function (e) {
alert(["window: Error", e.reason.message].join());
});
$.error = function (message) {
alert(["jQuery error", message].join());
};
So: am I missing anything (some Sentry config setting, other browser events that I should capture, etc.)?

Related

How to throw a javascript error during runtime via browser (Chrome)?

My objective: Test out my error handling functionality.
Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.
var a = undefined;
a.b.c // Breaks.
The above works, but I can't use it to test production site as the page is not required.
I was looking for a way to test it via the browser. I tried simply adding"
throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.
I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.
Any other easier ways to do this rather than the above?
I was looking for a way where I can do it via browser only.
Thanks.
You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:
Open the webpage
Open Chrome developer tools for that webpage
In Sources panel go to Overrides tab
Click Select folder for overrides and choose a folder on your computer
A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
In Sources panel go to Page tab
Locate the file in which you need to inject the "throw error" code
Right click and choose Save for overrides
Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.
If I got your question right, this is How you can do it from the console:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'throw new Error("Custom error thrown here")';
document.body.appendChild(script_tag);
Or if you want you can trigger it on click:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'window.document.onclick = function() { throw new Error("Custom error thrown here")}';
document.body.appendChild(script_tag);
And then you click anywhere on the page, to throw the error;
I would use the exec function which actually takes string and runs the code within at compile time.
exec('a.b.c')
You won't be able to throw an error inside your application from the console, since you are out of scope of the app.
Having said that, one slightly awkward way you could do this is by adding a breakpoint at the start of the javascript file.
Reload the page and your app will pause at the breakpoint - you can then modify the code as you need - like adding a throw new Error("something...") - and save your edits.
Then allow the code to run and you will see your error.
A downside is if you reload the changes will be gone, but I believe it's as close as you can get to modifying code at runtime.
Add this code to your production code
window.addEventListener('err', () => {
throw new Error('break it');
})
and when you want to create an error simply
dispatchEvent(new Event('err'))
in the console
You can use a global variable, which is accessible from your app and from debug console.
if (window.shouldThrow) {
throw new Error("Custom error thrown here");
}
This way you can turn on/off the exception throwing using the window.shouldThrow variable.
Try this way to catch error detail on run time
try
{
var a = undefined;
a.b.c // Breaks.
}
catch ( e )
{
alert("Error: " + e.description );
}

why dont i get "NetworkError" in javascript when i use <script src="false_ip">?

this is my simple script,
<script>
window.onerror = err;
var script = document.createElement('script');
script.src = "192.186.1.1.1.1.1";
script.onerror = err;
document.body.appendChild(script);
function err(msg, loc, a, b) {
alert(msg + "/" + loc);
}
</script>
but when i load this i get,
[object Event]/undefined
when i run the same on "firebug" i get detailed error like,
NetworkError: 404 Not Found - http://localhost/XSS/192.186.1.1.1.1.1"
So how can i get a detailed error .
try-catch alos doesnt work
try {
var script = document.createElement('script');
script.src = "192.186.1.1.1";
document.body.appendChild(script);
} catch(e) {
alert(e.name);
}
does that method will work only in old browsers ?
img.src also doesnt provide fire error handler. why?
var img = new Image();
img.src="gifffff/asasa/ss" ;
Firebug is not code, but a browser diagnostic tool running on the agent's behalf. (JavaScript cannot read the result of the firebug console.)
Now, for the cases:
The Image.error event never says why the loading failed. There is no provision to include the "reason" in the HTML specification; problem solved by not being a feature to begin with.
The catch doesn't work because there was no Exception thrown by the code.
The Image is still an Image and can still be added to the DOM
regardless of if the resource (eventually) fails to load.
(The src is still set to a valid URI component - it would have thrown an exception on an invalid/unknown URI scheme.)
Having this general limitation (on any [Image] resource, even on the same origin) also prevents violation of the Same-Origin Policy - and the ability for malicious code to run various network scanning attacks.

Javascript function not defined in FireFox only - indeed_clk is not defined

I'm at a loss to figure out why a JavaScript function is not defined.
It works on all browsers, and all versions of FireFox on my dev machine. But the error occurs for some users running FireFox.
The external JavaScript include file is provided by Indeed.com.
The include file that contains the function definition (indeed_clk) is
<script type="text/javascript" src="http://www.indeed.com/ads/apiresults.js"></script>
This line appears immediately after the head elememt
Further down the page, the indeed_clk function is referenced using the following pattern
<a onmousedown = "indeed_clk(this,'7832');" href="landing page..." >Click to view</a>
The error message is "indeed_clk is not defined"
A sample page that demonstrates the rendered html and Javascript code is
http://www.contractsforgeeks.com/TechJobs/All_States/All_Cities.aspx
Any suggestions as to why the function would not be defined in FF, and not work only for certain machine configurations would be appreciated.
Try changing:
indeed_clk(this,'7832')
To:
indeed_clk(this,'7832');"
I found a solution/workaround to the problem, but still don't understand why the error occurs.
It seems that the presence of an error Handler causes an error (but only in FF for some users)
An error handler was hooked up
(document).ready ( errorHandling);
function errorHandling()
{
window.onerror = function (message, url, line) {
var msg = message + "\n" + " url:" + url + "\nline:" + line;
alert(msg);
}
Disabling the error handling enabled the missing indeed_clk function to be found.

how to catch ALL javascript errors with window.onerror? (including dojo)

this question is a follow-up to javascript: how to display script errors in a popup alert? where it was explained how to catch regular javascript errors using:
<script type="text/javascript">
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
</script>
I tried it and found out that dojo erros like this one:
TypeError: this.canvas is undefined dojo.js (Row 446)
were not reported using this method, which leads me to my question:
How can I report all javascript errors using window.onerror (especially dojo errors)?
It could be Dojo is using proper Error handling methods (i.e. try-catch blocks) which prevents the exception from bubbling up and reaching the window container, on which you have registered the error handler.
If so, there is no way for you to do this. No error is going past the catch block, so no error handler is being called.
As pointed out by the comments, you can also use browser-specific debugging APIs like the Venkman hook and do break-on-error -- a solution that usually only works for privileged code (thanks to #Sam Hanes).
You can also do On(require, 'error', function () {}); to add error handling on DOJO's asynchronous script loader -- another point mentioned in the comments by #buggedcom
you can write code like this:
var goErrHandler=window.onerror;
goErrHandler= function(msg, url, linenumber) {
console.log('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
goErrHandler();
so in console you'll see some thing like this :
Error message: undefined
URL: undefined
Line Number: undefined
The better solution is to use try/catch, e.g.
try{
if(a=='a'){
}
}catch(e){
alert(e);
//or send to server
new Image().src='errorReport.php?e='+e;
}
Google Plus seems to use this.

Programmatically access webpage error details in browsers

Is there some way to access webpage warning/error details using JavaScript?
For instance, errors in IE show up in the bottom left corner like so:
I would like to able to access the details of this error (in IE as well as other browsers if possible) using JavaScript.
Any suggestions?
EDIT: I'm not looking for debuggers. I want to access the content of the error details/error console. Alternately, figuring out how to create a global exception handler equivalent for JavaScript would help too
You may want to use the window.onerror event. You can consider this event as a sort of global exception handler. The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message. (Source)
<script type="text/javascript">
window.onerror=function(msg, url, line){
alert('An error has occurred' + msg);
return true;
}
</script>
<script type="text/javascript">
// Syntax error
document.write('hi there'
</script>
You can also use traditional exception handling in JavaScript to catch run-time errors.
try
{
document.write(junkVariable)
}
catch (exception)
{
document.write(exception)
}
The output of the above would be:
‘junkVariable’ is undefined
EDIT: As noted by psychotik's comment, the window.onerror event does not work in Google Chrome. (Source)

Categories

Resources