Yaffle / EventSource

a polyfill for http://www.w3.org/TR/eventsource/
MIT License
2.12k stars 337 forks source link

Fix react native crash #228

Open MartinHarkins opened 8 months ago

MartinHarkins commented 8 months ago

If ever, here's a fix otherwise completely crashes the react-native apps (when in release mode).

Problem

Crash occurs whenever there is a connection error.

Essentially, since the error is thrown outside of the main run loop, react-native just crashes the app (there is no real way to avoid that currently). Throwing from within a setTimeout(), makes it that the error is uncatchable anyway.

Solution

This prevents the crash and reports the error. The readyState should be in CLOSED after this, which makes it consistent with the native EventSource behavior.

Note

As an aside, there's more fixes needed for SSE to work on expo & react-native, but that's not caused by this lib. I'll post links to the fix when i've created the relevant bugs

MartinHarkins commented 8 months ago

In the mean time I have a patch-package patch.

Add the file patches/event-source-polyfill+1.0.31.patch

diff --git a/node_modules/event-source-polyfill/src/eventsource.js b/node_modules/event-source-polyfill/src/eventsource.js
index cd2de7c..92862c0 100644
--- a/node_modules/event-source-polyfill/src/eventsource.js
+++ b/node_modules/event-source-polyfill/src/eventsource.js
@@ -992,7 +992,10 @@
         abortController = transport.open(xhr, onStart, onProgress, onFinish, requestURL, withCredentials, requestHeaders);
       } catch (error) {
         close();
-        throw error;
+
+        var event = new ErrorEvent("error", {error: error});
+        es.dispatchEvent(event);
+        fire(es, es.onerror, event);
       }
     };