How do I test that Sentry is reporting errors? - javascript

I just installed Sentry for a client-side JavaScript app using the standard code snippet they provided. How do I test that it's working properly? I've tried manually throwing an error from my browser console and it didn't appear in Sentry. Is there any documentation on the right way to do this?

Verify (newer)
myUndefinedFunction();
Verifying Your Setup (older)
Sentry.captureException(new Error("This is my fake error message"));
https://docs.sentry.io/platforms/javascript/?platform=browser#verifying-your-setup
May be worth double-checking your setup (or updating) and config too.

The browser console can not be used as it is sandboxed. A simple trick is to attach the code to an HTML element like this:
<h1 onClick="throw new Error('Test')">
My Website
</h1>
And click on the heading afterwards.
This can be done in the browser inspector and so your source code doesn't have to be modified.

One way to generate an error in Sentry is to call a function that is not defined.
Note: This cannot be done in the console - it must be in the code.
Try adding this to your code (taken from the docs):
myUndefinedFunction();
If your code build doesn't allow this due to tests/linting you might be able to use:
window.myUndefinedFunction()
You should then see error in your browser console and in the Sentry dashboard.
Have a read of the Docs for more info.

Raven.captureMessage('Broken!') is a good place to start (also pulled from Sentry docs). If that fails to send, the Raven client isn't being initiated.

If you can't or don't want to use an undefined function to test Sentry is sending errors, you can also use the Debugger in Chrome's DevTools by:
Adding a breakpoint in your code e.g. for a click event handler
Trigger that event e.g. click a button
When the breakpoint hits in the console, set a function/variable that is needed for execution to undefined
Press play/continue in DevTools to then see the Error output
e.g.
1: function onClick() {
2: api.sendSomeEvent();
3: }
Add a breakpoint in the body of the onClick event handler (Line 2), trigger the event. When execution is paused: in your console enter something like api = undefined and hit enter to update the state. Then continue execution (click the play button), where you should see an error (ala api is undefined) that Sentry should then send for you.
Note: this works for any environment, though you may need to be clever with finding your events in minified code ;)

Related

"A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received", What does that mean?

I'm working on a React application and I use some npm modules, one of which I had to build myself. (my NPM package:
https://www.npmjs.com/package/modale-react-rm).
It is a simple modal that opens and closes with a useState().
After importing my package, I have an error in my console that appears suddenly after a few seconds without performing any actions.
Uncaught (in promise) localhost/:1
>{message: 'A listener indicated an asynchronous response by r…age channel closed before a response was received'}
message: "A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received"
>[[Prototype]]: Object
>constructor: ƒ ()
>[[Prototype]]: Object
/* sometimes there are specific elements in addition but I could not check when they appear and when not */
Promise.then (asynchrone)
(anonyme) #content_script_bundle.js:108
handleNewFeatures #content_script_bundle.js:101
handleUpdatedNodes #content_script_bundle.js:101
(anonyme) #content_script_bundle.js:101
childlist(asynchrone)
0 #purplebox.js:1
(anonyme) #purplebox.js:1
v #purplebox.js:1
It doesn't block my pages, nor does it prevent the proper functioning of its features, but it's an error and I think it should be fixed and maybe help other people who have the same problem.
I specify that I do not make any async request in this project. Everything is local and the few data I use are directly imported in raw.
I don't know where Purplebox.js comes from as well.
This issue is a cross-origin request issue and it is caused by various Chrome Extensions.
I had this too in my Angular app and after testing it in the incognito mode, the error didn't show up anymore.
More info: Google Forum
/Edit:
If you are an extension developer coming here: You need to return true when fetching data from cross-origins. More info: Chromium Project
In my case, it is caused by Ghostery extension, if this error appears in your local host, you need to add it to the trusted sites list of Ghostery and the error will be gone.
It has been discussed in the webextension-polyfill library, which is used by many extensions (including Ghostery). There was a recent change in Chrome that introduced to the error message.
For projects that are using the polyfill, I would expect the warning to go away if a fix is merged. Note that the polyfill library is used, since only Firefox implements the new promised-based runtime.onMessage, while Chrome still enforces the original callback-style API.
Note that there is an open pull request in the webextension-polyfill library already. It has not been merged, but according to my tests, it solves the problem. So, if you need a quick fix for a project that uses the library internally, you can manually apply the patch with patch-package. For instance, this is how such a change would look like in Ghostery.
The background script (service worker in MV3) could be going to inactive state without sending a response back to a message it received from a content script.
Example:
Background script:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// ... handle message
return true // Error message says you already return true
})
Most MV3 APIs are asynchronous and can return promises when it makes sense to do so. (In some cases, like event listeners (e.g.: chrome.tabs.onRemoved), returning a promise wouldn't make sense). Reading a response back however can be done using callbacks or promise-style.
Content script: method 1 to read response:
chrome.runtime.sendMessage('ping', (response) => { /* read response */ })
Content script: method 2 to read response:
chrome.runtime.sendMessage('ping').then(response => { /* read response */ })
The issue you are facing is this: background script does not invoke sendResponse() for one/more messages it received and went inactive (causing the message channel to close). However, the content script that sent the message is waiting for the response.
Please check your message senders & handlers.
I had the same error. I removed the Tampermonkey extension and tweaked my AdBlock extension and then it worked for me.
I encountered the same issue couple of days ago, and found out that the source of error is located in the background.js.
it's caused by the runtime Message Handler. to solve it, just add a third parameter as a callback function to chrome.runtime.onMessage.addListener.
forgot how i found the solution, but it works for me.
// to avoid the error, the parameter [sendResponse] is necessary!
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
// do something ...
// this line seems meaningless but you have to invoke it to avoid error.
sendResponse({damn: true});
});
This error is related to ad blockers or similar. Just exclude the site for this application.
In my case it was AdBlock app. It kept showing this error in the console when working with LiveServer or FiveServer. It does not affect anything, but it is very annoying
I had the same error on my react app when i introduced an infinite loop through useEffect, the thing is that you most likely won't see too much change in your app or problem. For me it even helped reload some state for functions that i was still to write but over time it will introduce bugs and performance issues.
Avast Online Security & Privacy 22.11.173 is causing the same issue.
I had the same issue on my Windows 11 machine.
I added these lines at the bottom of the hosts file in the drivers/etc directory:
127.0.0.1 localhost
::1 localhost
This solved the problem for me.
I faced the same error. Where class Component didn't show any response over display.
Solution : Syntax error in spelling "render" => ~"rendor"~

JSON Parse error: Unrecognized token '!' - error caught by Sentry

The error in the title is caught by Sentry (an error tracking tool). Below is a screenshot from Sentry - showing the stack trace.
Note: the script /en_US/iab.autofill.payment.js where handleMessage is located is loaded from Facebook (link here), and I couldn't find this script in the javascript bundle, nor anything related to it. I assume it's loaded by a 3rd party script - I'm using Google Tag Manager (which is also loading Facebook Pixel), Segment (loading Hotjar and Mixpanel), and Snapchat. The error started to appear without any changes in these scripts or the services that they're sending data to.
Note 2: It seems that the error is triggered quite often, about 10-15% of the time. I tried to reproduce it but given that it's a handled error, it doesn't show in the dev console.
Any direction on where to look would be much appreciated.
I'm seeing this a lot, and it seems to be coming 100% from users using Facebook browser on iOS (I guess this is the browser you see when you're using the Facebook app).
I tried to debug this with a snippet:
<script>
window.addEventListener('message', function (e) {
console.log(e);
JSON.parse(e.data);
console.log('foo');
}, false);
</script>
This is from the library you linked. Assuming that e.data is JSON string (not e.g. an object?), without any safeguard seems to be breaking things.
The second console.log doesn't fire, so I think this is causing some unexpected behaviours in my case (buttons not reacting to clicks with js listeners etc)
I don't know if there is a workaround or a way to protect from this in Facebook embedded browser (I guess it's loaded there)
Looking forward to hear more info
i have meet that too, its because the one script facebook inject in. will postMessage(Object), but the another script will listen the message and try to JSON.parse an object ,so it will came out a error. u can use 'vconsole' lib, and add a window.addEventListener('message',(e)=>{console.log(e.data)}) and u can see that
Apparently, the issue went away after a couple of weeks without changing anything on my side.

Is there a way to get list of errors in chrome/firefox which happened throughout the web page

I have an html file which may contain many img tags and also it will have JS like below.
If I try to load this page in chrome and also click the button clickMe I get the below errors in console.
I know that using window.onerror I can handle/capture ReferenceError and may be save it for later. But, is there any error stack from where I can get all the list of errors which has happened during the life-cycle of the web page. Because, I am not able to capture ERR_FILE_NOT_FOUND error.
Please let me know whether it is possible and if so how ?
ERR_FILE_NOT_FOUND error is not JS error so it can't be caught globally, only way send ajax file existing request. Also for image you can use onerror event to caught this error, for audio you can use source tags and etc.. But for globally there is no way to catch it.
Also for queueing error I'm recommending use Sentry.
Not quite understand your question. However, if you want to catch your javascript error and log to the console do like this:
try {
dosomething...
}
catch(err) {
console.error(err.message);
}
There are 4 level of logging to the console:
console.error(message);
console.log(message);
console.warn(message);
console.info(message);
On the Console tab of the Firebug tool in Chrome, you can filter out the type of logging. You can click on the Preserve log checkbox so all the log will continue to append to the console.
Other errors report from the browser, that is those you don't capture from your script, also go here.
If you really want to capture an image load fail there are couple ways to do it. One way is something like this:
<img src="smiley.gif" onerror="console.error('Fail to load smiley.gif');" />
See this link if you want to enable debug to a file for google chrome: https://www.chromium.org/for-testers/enable-logging

Capturing JS errors in Chrome

I'm capturing js errors in the application with window.onerror, but the thing is - in Chrome if dev tools isn't opened - then the url parameter passed to onerror handler always equals to the opened url.
While if dev tools is opened - then the url points to the exact .js file the caused the js error.
How do you deal with it? Are there any workarounds?
And to be more clear - here are 2 results:
Uncaught ReferenceError: a is not defined index:122 - this was received after fetching a page
Uncaught ReferenceError: a is not defined List.js:122 - this was received after fetching the same page with dev tools opened. This is an expected result - I've put a(); call to the List.js file for testing.
UPD: this is done for functional testing (using selenium webdriver) - I want to capture js errors for further investigations.
Let's pose the following architecture:
window.addEventListener("error", handleException, false);
function handleException(I_sMsg) {
if (I_sMsg.stack) {
sMsg = I_sMsg.stack.replaceAll(getBaseURL(), "");
alert(sMsg);
} else if (I_sMsg.message) {
alert(I_sMsg.message);
}
return cancelEvent(I_sMsg);
}
Now any throw new Error("description"); will go through the first part of the if statement and have a nice stack for you to parse with the urls.
It also works for unexpected exceptions, having as a result the following message (in this case after calling the unexisting bibi() function)
After further investigation, my framework is using some kind of home made job management (as shown in the stack actually) where every single action belongs to a job.
The job execution method is the following (simplified)
try {
oTask.func.apply(oTask.obj, oTask.prms);
} catch(ex) {
handleException(ex);
return false;
}
So it means every single execution is encapsulated within this single try catch block. As you see, the exception is caught, and passed to the handler. Not the error.
I though it was working in the other file but it was because the call was encapsulated, while within the api.js file directly it was a free call not managed by the framework.
More of a something to try answer really but it might help.
Chrome recently added chrome://inspect/ to the list of handy URLs (see chrome://chrome-urls/ for the complete list). I cannot find the tweet or blog post I read about this unfortunately but I think it was within the last month. The URL works on Chrome 28 for sure.
chrome://inspect/ lists all open tabs with an inspect link which redirects back to the existing open page but also opens DevTools.
I'm thinking that the selenium test could open the site under test in one tab and in a second tab open the inspect page, follow the inspect link back to the test page but this time with DevTools open, allowing window.onerror to capture better errors.
Something like:
document.getElementsByClassName('row')[n].getElementsByTagName('a')[0].click()

Facebook like button in site that uses post message spams console

I have a site that uses a lot of postMessage communication between iframes. Putting a Facebook like button in my site causes my debug console to get spammed with messages like
Received message of type object from [domain], expected a string.
This makes development very difficult. Is there any way to prevent this extra logging from occurring? I am new to using facebooks apis so I'm hoping I'm just missing something simple. They can't possibly assume that no one besides them will ever use postmessage.
Thanks!
Actually, disabling console.log is a horrible answer. What if we want to use console.log, but just want to stop the spamming error message? What is causing it? How do we actually fix it?
Actually that's not an extra logging. It's from the Facebook SDK. Simply you can uglify the sdk for removing all console from the library.
1.Download the sdk. https://connect.facebook.net/en_US/sdk.js
2.Uglify it for removing console logging (production version.)
https://github.com/mishoo/UglifyJS
3.Use it in your site.
Another link which may help you:
http://elijahmanor.com/grunt-away-those-pesky-console-log-statements/
You could simply "unset" the console.log function, by doing something like:
console.log = function(){}
Save it in another variable first, for example:
var originalLog = console.log;
Now when the Facebook API tries to use the log function nothing will happen. If you need to use the log function, just enable it first by setting it back to your saved originalLog variable and unset it when you are done using it. Unhandled errors will still show up in your console, regardless of what you have done to the log function.
In my case this was caused by the FVD Video Downloader extension, so maybe you should disable all browser extensions and see if that solves the issue, then enable them back one by one to find the culprit.

Categories

Resources