简体   繁体   English

try catch 不适用于 sse

[英]try catch doesn't work with sse

This is the code, PS: the service httpd in s10 is stopped这是代码, PS:s10中的服务httpd被停止

        try {
            var source = new EventSource("http://s10/server.php");
            console.log(source);
        } catch (e) {
            console.log("ADSfasfasfasdfasdfas" + e)
        }

this is the console:这是控制台:在此处输入图片说明

why the heck the try catch is not catching the error ??为什么 try catch 没有捕捉到错误?

ofcourse I have onerror event and onclose event:当然我有 onerror 事件和 onclose 事件:

        source.addEventListener('error', function(e) {
            if (source.readyState == 2) {
                connectionClosed();//to change some style
                console.log("Disconnected");
            }

        }, false);

        source.onerror = function(e) {
            if (source.readyState != 0) {
                connectionClosed();//to change some style
                console.log("Disconnected");
            }
        };
        source.onclose = function() {
            connectionClosed();//to change some style
            console.log('Connection closed');
        }

When I run this in the Console on an arbitrary URL that isn't set up to handle SourceEvents, the Console successfully logs a SourceEvent instance.当我在控制台中在未设置为处理 SourceEvents 的任意 URL 上运行此程序时,控制台成功记录了 SourceEvent 实例。 This is similar to what you're describing.这与您所描述的类似。

源事件

So my guess here is that there's no error to catch.所以我的猜测是没有错误可以捕捉。 The SourceEvent instance is successfully constructed, even though there's no actual connection.即使没有实际连接,SourceEvent 实例也已成功构造。 If you want to detect if the connection is working, use the EventSource.readyState property.如果要检测连接是否正常工作,请使用EventSource.readyState属性。

In my screenshot you can see that readyState = 0 , which means that the connection is "connecting", but in reality it's never going to finish connecting because the server on the other side isn't set up to handle SourceEvents.在我的屏幕截图中,您可以看到readyState = 0 ,这意味着连接正在“连接”,但实际上它永远不会完成连接,因为另一端的服务器未设置为处理 SourceEvents。

https://developer.mozilla.org/en-US/docs/Web/API/EventSource/readyState https://developer.mozilla.org/en-US/docs/Web/API/EventSource/readyState

I'm testing the same thing, the onerror doesn't provide really useful info.我正在测试同样的东西, onerror没有提供真正有用的信息。 For example, if you shut down your server or if you send an empty response while your client is connected, you can't detect programmatically on the client side the specific cause, I can see that just inspecting the dev console.例如,如果您关闭服务器或在客户端连接时发送空响应,则无法在客户端以编程方式检测到具体原因,我可以看到仅检查开发控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM