Inspecting a caught error in a React Native app - javascript

I'm working with a React Native app in a dev environment and am running into an error whereby a toast is shown after I try to upload a file. The code is similar to the following:
function* onUploadPrompt(action: Action): Saga<*> {
try {
yield put(ProfileCertificateUpload.uploadEnd());
} catch (err) {
debugger;
// if upload fails show a toast to user so they may retry
yield put(Toast.showNegative(str.uploadFail()));
yield put(ProfileCertificateUpload.uploadEnd());
}
}
Note that I've set a debugger breakpoint in the catch block. If I stop the package manager and start it again (using yarn start) and go through the flow to trigger the error, I hit the breakpoint:
What puzzles me is that I don't see err anywhere; I can't inspect it. Shouldn't the err error variable be in scope where I set my breakpoint, so that I can have a look at the error and learn more about it?

Instead of debugger, put console.log(‘error:’, err); and check your console to see what the error actually is.

Related

Catch an errors in ElectronJS [duplicate]

I'm currently building an application for file backup, and it got quite a bit of reading and writing to the filesystem. Most of it works great, but I'm struggling a bit with the error handling of the app.
In the screenshot below the last path is not a valid directory and return an exception as you can see.
function getTotalSize(pathToDir, dir) {
fs.readdir(pathToDir, function(err, files) {
if (err) {
// handle my error here
throw new Error('something bad happened');
return;
}
// continue if no errors :)
My question is, is it possible to replace the standard error window with my own? Or in some cases ignore the pop up of the error window? First time working with Electron so sorry if this is an obvious one.
Thanks!
When you throw the error from readdir it gets caught by the top-level uncaughtException handler, indicated by the the first line: "Uncaught Exception".
What you need to do is add your own custom handler for the uncaughtException in your main process and show whatever dialog you want from there.
Take a look at the dialog module.
As an example, you can use the dialog.showMessageBox method to configure all sorts of things about the error dialog like this:
process.on("uncaughtException", (err) => {
const messageBoxOptions = {
type: "error",
title: "Error in Main process",
message: "Something failed"
};
dialog.showMessageBoxSync(messageBoxOptions);
// I believe it used to be the case that doing a "throw err;" here would
// terminate the process, but now it appears that you have to use's Electron's
// app module to exit (process.exit(1) seems to not terminate the process)
app.exit(1);
});

Cypress error when testing nested iframes in headless mode - race condition

I am testing a web app and the test runs reliably in headed mode (cypress open) but has errors in headless mode (cypress run), so it's likely a race condition that I cannot resolve. The error message is:
[36819:0223/163815.745047:ERROR:system_services.cc(34)] SetApplicationIsDaemon: Error Domain=NSOSStatusErrorDomain Code=-50 "paramErr: error in user parameter list" (-50)
This error is mentioned again when Cypress creates a video of the incident:
- Started processing: Compressing to 32 CRF
2022-02-23 17:00:19.700 Cypress Helper[37571:416134] In -[NSApplication(NSQuietSafeQuit) _updateCanQuitQuietlyAndSafely], _LSSetApplicationInformationItem(NSCanQuitQuietlyAndSafely) returned error -50
- Finished processing: /Users/malte.wirz/Documents/iframes-cypress-issue/cypress/videos/iframe-github.js.mp4 (3 seconds)
I created a demo repository here. To reproduce, clone it, run yarn to install, and yarn cypress:run. The test does pass, but with the error mentioned above.
I assume that the error stems from accessing the nested iframes and I tested 5 different approaches so far, but to no avail. I especially made sure that the function getIframeBody waits until each iframe and the requested element is ready. The error also creates a video, but you can only see the successful run, the error message is not visible there.
Any help on how to debug this further is much appreciated.
describe('Testing Iframe within Iframes', () => {
it('Visits the iframe website and accesses the iframe within the iframe', () => {
const getIframeBody = (iframeSelector, elementSelectorInIframe) => {
return cy
.get(iframeSelector)
.its('0.contentDocument.body', {timeout: 30000})
.should((body) => {
expect(Cypress.$(body).has(elementSelectorInIframe).length).gt(0)
})
.then(cy.wrap)
}
// Visiting the page index.html and getting iframe A
cy.visit('index.html').contains('XHR in iframe')
getIframeBody('iframe[data-cy="bankid"]', 'iframe[src="https://tools.bankid.no/bankid-test/auth"]').as('iframeA')
cy.get('#iframeA').within(() => {
getIframeBody('iframe[src="https://tools.bankid.no/bankid-test/auth"]', 'iframe[src^="https://csfe.bankid.no/CentralServerFEJS"]').as('iframeB')
cy.get('#iframeB').within(() => {
getIframeBody('iframe[src^="https://csfe.bankid.no/CentralServerFEJS"]', 'input[type="tel"]').as('iframeC')
// Now we are in the right place and it finds the correct input element.
// However, normal cypress command .type() fails and we have to use library cypress-real-events,
// which provides an event firing system that works literally like in puppeteer
cy.get('#iframeC').find('input[type="tel"]').should('be.visible').realType('12345678912')
// But for the button below, this library now doesn't help anymore:
// "Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'."
// This was solved by using {scrollBehavior:false}.
cy.get('#iframeC').find('button[type="submit"]').should('be.visible').first().realClick({scrollBehavior:false})
})
})
})
})
I got some feedback that the above "ERROR:system_services.cc(34)" is not critical and does not cause flaky or unsuccessful tests, therefore there are no action points.

How to log error in catch statement in sentry

I am new to Sentry and I want to log an error manually.
For some reason I am unable to find in their docs, how I can achieve this
I am using RN project but from their docs, RN extends JS sdk
Consider a function as simple as this
const logErrorIntentionally = () => {
try {
} catch (error) {
//throw sentry error here
}
}
How can I log thrown error in sentry? from my catch block.
According to the docs:
import * as Sentry from '#sentry/browser';
try {
aFunctionThatMightFail();
} catch (err) {
Sentry.captureException(err);
}
For custom messages:
import * as Sentry from '#sentry/browser';
Sentry.captureMessage("Something went wrong");
The most common form of capturing is to capture errors. What can be captured as an error varies by platform. In general, if you have something that looks like an exception, it can be captured. For some SDKs, you can also omit the argument to captureException and Sentry will attempt to capture the current exception. It is also useful for manual reporting of errors or messages to Sentry.
You can read more from the official docs https://docs.sentry.io/platforms/react-native/usage/

How to ignore the "ResizeObserver loop limit exceeded" in TestCafe

I'm currently using TestCafe for some e2e tests. I've run into the following error
1) - Error in Role initializer -
A JavaScript error occurred on "http://localhost:3000/".
Repeat test actions in the browser and check the console for errors.
If you see this error, it means that the tested website caused it. You can fix it or disable tracking JavaScript errors in TestCafe. To do the latter, enable the "--skip-js-errors" option.
If this error does not occur, please write a new issue at:
"https://github.com/DevExpress/testcafe/issues/new?template=bug-report.md".
JavaScript error details:
ResizeObserver loop limit exceeded
No stack trace available
A bit of research suggests that the ResizeObserver loop limit exceeded issue is a benign error.
However, it causes my test to fail. Is there any way I can ignore this specific error without using the --skip-js-errors flag, as I would prefer to not ignore all JavaScript errors because of this one issue
As far as I understand, this error occurs when ResizeObserver cannot deliver all observations within a single animation frame. A person who is the author of the ResizeObserver specification assures that it can be safely ignored: ResizeObserver loop limit exceeded
Chrome and Firefox don't display it by default. You can only catch it when you set an explicit onerror handler:
window.onerror = e => console.log(e);
You can see that this error is reproduced on the Google Sign In page without TestCafe. I added an onerror handler to the page and got ResizeObserver loop completed with undelivered notifications. in Firefox and ResizeObserver loop limit exceeded in Chrome.
As a workaround, you can specify the --skip-js-errors flag when starting TestCafe. I admit that it's not the best approach since you will suppress all Javascript errors on a tested page.
A more reliable way is to add a global window error handler explicitly in your tests via client scripts:
import { Selector, t } from 'testcafe';
// Constants
const gmailEmailInput = Selector("#identifierId");
const gmailNextButton = Selector(".CwaK9");
const gmailPasswordInput = Selector("input[type='password']");
const explicitErrorHandler = () => {
window.addEventListener('error', e => {
if(e.message === 'ResizeObserver loop completed with undelivered notifications.' ||
e.message === 'ResizeObserver loop limit exceeded') {
e.stopImmediatePropagation();
}
})
}
fixture("Gmail login test")
.clientScripts({ content: `(${explicitErrorHandler.toString()})()` });
test("Not trigger JS error when logging in to Gmail", async testController => {
await testController
.navigateTo("https://mail.google.com")
.typeText(gmailEmailInput, "someuser#gmail.com")
.click(gmailNextButton)
.typeText(gmailPasswordInput, "password")
});
I copypasted the workaround from here.

JS - how to prevent script from stopping after thrown error

How can I prevent the script from stopping after an error has been thrown? Is there something like exception handling in JS?
Console text
Not allowed to load local resource: file:///C:/Users/Temp/image.png
Javascript does have exception handling. There are two possible types of error you can encounter:
1) Places in your application where you proactively guard against errors being thrown, for example, AJAX request. You can handle them like this:
try {
AJAX-code or other code susceptible to errors
} catch(error){
// Log error
}
2) Script errors or compile-time error, for example, undefined variables. In browsers, window.onerror is a global event handler which is called on script or compile errors. However, it's implementation is inconsistent across browsers. You can use it like this:
window.onerror = function(message, url, lineNo) {
// Code to handle the error
}
The main problem with onerror is that no stack trace is passed through which is not very helpful. However, Chromium has added column number and errorObj, so hopefully other browsers will implement the same in near future.
There surely is: try {} catch (exception) {}
Sure, wrap your code inside try/catch:
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
You can use a try/catch/finally block to handle errors:
try {
// Whatever you need
} catch(error) {
// Handle error if one occurs
} finally {
// Last resort
}
Note that you can have multiple catch blocks in-between your try and finally as needed.
Here's some more information.

Categories

Resources