douju1953 2015-06-29 21:22
浏览 100

如果抛出异常,则不会调用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.

  • 写回答

2条回答 默认 最新

  • douluo1330 2015-06-29 21:26
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序