如果抛出异常,则不会调用addEventListener

I am trying to implement Server-sent-events communication between my client and my server.

I have implemented it and it works perfectly except when the server return exceptions.

I am not sure why the exception message is not being returned to the client after the exception.

Here is how my listener is written

    var evtSource = new EventSource('poll.php');

    evtSource.addEventListener("getMessagingQueue", function(e) {
        console.log(e);
        var data = JSON.parse(e.data);
        console.log(data);
        processServerData(data);

    }, false);

Below is my PHP code. (ie. poll.php) file

ini_set('display_errors', 0);
set_time_limit(0);

header("Content-Type: text/event-stream" . PHP_EOL);
header("Cache-Control: no-cache" . PHP_EOL);

try {

    $sleepTime = 1;
    $url = '';
    $loggedIn = false;

     if( !isDefinedConstents('ICWS_USERNAME', 'ICWS_PASSWORD', 'ICWS_STATION_NAME', 'ICWS_SERVER', 'ICWS_PORT') ){
        throw new exception('Missing Credentials');
    } else {

        $scheme = 'http';
        if(ICWS_SECURED){
            $scheme = 'https';
        }


        $url = sprintf('%s://%s:%s@%s:%s', $scheme, ICWS_USERNAME, ICWS_PASSWORD, ICWS_SERVER, ICWS_PORT);

        //configure the connection
        $conf = new ICWS\Config\Config($url, ICWS_STATION_NAME);    

        //create a new instance of icws

        $icws = new ICWS\Connection($conf); 
        $messaging = new ICWS\Messaging($icws);

        $loggedIn = $icws->isLogged();

    }

    if(!$loggedIn){
        throw new exception('Something Went Wrong when trying to login');
    }

    while($loggedIn){

        $messaging->processMessages();

        $result = array_merge( (array) $messaging->getCallsQueue(), (array) $messaging->getCurrentUserStatusQueue()) ;

        displayResults($result);

        sleep(1);

    }

} catch(Exception $e){

    $result = array('userStatus' => array('statusId' => 'You are not logged in!',
                                       'isLoggedIn' => false,
                                       'icwsDescription' => $e
                                       )
                    );

    displayResults($result);


}


function displayResults($result){

    echo 'event: getMessagingQueue' . PHP_EOL;
    echo 'data: ' . json_encode(  $result ) . PHP_EOL . PHP_EOL;
    ob_end_flush();
    flush();
}



function isDefinedConstents(){

    $args = func_get_args();

    foreach($args as $v){
        $value = constant($v);
        if( !defined($v) || empty($value) ){
            return false;
        }
    }

    return true;
}

How do I get the listener to get the message even if the there is exceptions?

EDITED When I execute this code after the addEventListner line

evtSource.onerror = function(e) {
                console.log(e);
            };

This is what I get

error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, timeStamp: 1435614201283000, originalTarget: EventSource, explicitOriginalTarget: EventSource, NONE: 0 }

It seems that the Exception thrown by PHP server cause the entire call to fail.

dongshi8038
dongshi8038 这不是json的问题。如果是那么console.log(e);应该给我一些东西,但就我而言,它什么也没给我。
大约 5 年之前 回复
doujun1495
doujun1495 我刚刚更新了我的问题。当服务器抛出异常时,整个调用似乎失败了
大约 5 年之前 回复
drvvvuyia15070493
drvvvuyia15070493 这不是json的问题。如果是那么console.log(e);应该给我一些东西,但就我而言,它什么也没给我。我认为问题是由于异常,整个调用失败了
大约 5 年之前 回复
donglei1616
donglei1616 addEventListener查看输出并仅发送数据提取:{“userStatus”:{“statusId”:“您尚未登录!”,“isLoggedIn”:false,“icwsDescription”:{}}}
大约 5 年之前 回复
duanbei1598
duanbei1598 它具有相同的输出,就好像没有异常一样。它看起来像这个事件:getMessagingQueuedata:{“userStatus”:{“statusId”:“你还没有登录!”,“isLoggedIn”:false,“icwsDescription”:{}}}
大约 5 年之前 回复

2个回答

Most likely, your Javascript code is having trouble JSON.parseing the PHP exception returned because it is not valid JSON. This will cause an uncaught exception in your Javascript code, ending the execution.

The way to get around this is to throw the exception in a way the Javascript can handle. Instead of throwing the exception, try something like die("data: ". json_encode(array("exception" => "Missing Credentials.")))

Also, try surrounding your JSON.parse() with a try catch block, and print the exception to the console.

There may also be an uncaught exception being thrown in your processData function, but we have no way of knowing without seeing the code.

douzai2562
douzai2562 这不是json的问题。 如果是那么console.log(e); 应该给我一些东西,但就我而言,它什么也没给我。
大约 5 年之前 回复



我通过在两个标题下添加 ob_end_clean(); </ code>来解决问题(... 。</ code>行</ p>
</ div>

展开原文

原文

I solved the problem by adding ob_end_clean(); below the two header(.... lines

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐