如何在signalr java客户端中捕获异常

时间:2015-11-22 15:30:46

标签: java android signalr signalr.client

我在Asp.net web api中运行信号器集线器。我可以通过从dot net客户端调用hub和client函数来发送和接收消息。现在我试图在java客户端(Android平台)上实现相同的功能。我设法连接到集线器并接收消息。但是,当我发送消息时,它会抛出异常。发送消息(调用集线器功能)时,集线器功能被成功调用,另一侧也接收消息。但是,来自集线器的响应(返回发送方)是html格式而不是json。这会在客户端引发异常。当消息传递时,我可以暂时忽略异常。但是我无法捕获异常,因此android进程被终止。

客户代码:

private HubConnection mConnection;
private HubProxy mProxy;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initializeSignalr();
    connectNotificationHub();

    Button btnSend = (Button) findViewById(R.id.btnSend);
    View.OnClickListener oclBtnSend = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                mProxy.invoke("SendToOperators", "21", "test message", "chat").done(new Action<Void>() {
                    @Override
                    public void run(Void obj) throws Exception {
                        System.out.println("SENT!");
                    }
                }).onError(new ErrorCallback() {
                    @Override
                    public void onError(Throwable throwable) {
                        System.out.println("ERROR!");
                    }
                }).get();
            } catch (Exception e) {

            } 
        }
    };
    btnSend.setOnClickListener(oclBtnSend);
}

    public void initializeSignalr(){
    Platform.loadPlatformComponent(new AndroidPlatformComponent());
}

public void ShutdownSignalr(){
    if(mConnection!=null){
        //mConnection.disconnect();
        mConnection.stop();
        mConnection=null;
    }
}

public void connectNotificationHub()
{
    String server = REST_SERVICE_URL+"signalr";
    mConnection = new HubConnection(server,"userName="+IMUSER_PFX+"_driver"+Integer.toString(DriverID),true, new Logger() {
        @Override
        public void log(String message, LogLevel level) {
            if (level == LogLevel.Critical) {
            Log.d("SIGNALR", level.toString() + ": " + message);
            }
        }
    });

    mProxy = mConnection.createHubProxy("NotificationHub");

    mProxy.subscribe(new Object() {
        @SuppressWarnings("unused")
        public void addMessage(String name, String message) {
            Log.d("Message: ", message);
        }
    });

    mConnection.error(new ErrorCallback() {
        @Override
        public void onError(Throwable error) {
            error.printStackTrace();
        }
    });

    SignalRFuture<Void> awaitConnection = mConnection.start();
    try {
        awaitConnection.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

在dot net客户端中,如果服务器不可用,则无法使用try catch clock捕获异常但是我可以通过订阅错误回调来解决它

mConnection.error(new ErrorCallback() {
    @Override
    public void onError(Throwable error) {
        error.printStackTrace();
    }
});

在我发送消息时的java客户端

try {
            mProxy.invoke("SendToOperators", "21", "test message", "chat").done(new Action<Void>() {
                @Override
                public void run(Void obj) throws Exception {
                    System.out.println("SENT!");
                }
            }).onError(new ErrorCallback() {
                @Override
                public void onError(Throwable throwable) {
                    System.out.println("ERROR!");
                }
            }).get();
        } catch (Exception e) {

        }

它抛出json解析异常

11-22 03:42:27.776  19661-20016/com.eb5.uvexa.uvexadriver D/SIGNALR﹕ Critical: HubConnection - Error: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected EOF at line 1 column 10
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected EOF at line 1 column 10
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at com.google.gson.JsonParser.parse(JsonParser.java:65)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at com.google.gson.JsonParser.parse(JsonParser.java:45)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at microsoft.aspnet.signalr.client.transport.TransportHelper.processReceivedData(TransportHelper.java:41)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at microsoft.aspnet.signalr.client.Connection.processReceivedData(Connection.java:733)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at microsoft.aspnet.signalr.client.Connection.access$0(Connection.java:728)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at microsoft.aspnet.signalr.client.Connection$1.onData(Connection.java:302)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at microsoft.aspnet.signalr.client.transport.HttpClientTransport$2.onResponse(HttpClientTransport.java:122)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at microsoft.aspnet.signalr.client.http.java.NetworkRunnable.run(NetworkRunnable.java:82)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at java.lang.Thread.run(Thread.java:864)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ Caused by: com.google.gson.stream.MalformedJsonException: Expected EOF at line 1 column 10
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1310)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at com.google.gson.stream.JsonReader.peek(JsonReader.java:390)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ at com.google.gson.JsonParser.parse(JsonParser.java:60)
11-22 03:42:27.786  19661-20016/com.eb5.uvexa.uvexadriver W/System.err﹕ ... 8 more

我收到了另一方的消息。但是来自中心的响应是html格式而不是json。我确定这是一个错误,我将在github signalr问题跟踪器上发布。但是我需要一种方法来阻止Android客户端崩溃。

来自中心的html响应

11-22 03:42:27.766  19661-20016/com.eb5.uvexa.uvexadriver D/SIGNALR﹕ Verbose: serverSentEvents - Response received
11-22 03:42:27.766  19661-20016/com.eb5.uvexa.uvexadriver D/SIGNALR﹕ Verbose: serverSentEvents - Read response to the end
11-22 03:42:27.776  19661-20016/com.eb5.uvexa.uvexadriver D/SIGNALR﹕ Verbose: serverSentEvents - Trigger onData with data: {"I":"1"}<!DOCTYPE html>
<html>
<head>
<title>Runtime Error</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
@media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
@media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a &lt;customErrors&gt; tag within a &quot;web.config&quot; configuration file located in the root directory of the current web application. This &lt;customErrors&gt; tag should then have its &quot;mode&quot; attribute set to &quot;Off&quot;.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
&lt;!-- Web.Config Configuration File --&gt;
&lt;configuration&gt;
&lt;system.web&gt;
&lt;customErrors mode=&quot;Off&quot;/&gt;
&lt;/system.web&gt;
&lt;/configuration&gt;</pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the &quot;defaultRedirect&quot; attribute of the application&#39;s &lt;customErrors&gt; configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
&lt;!-- Web.Config Configuration File --&gt;
&lt;configuration&gt;
&lt;system.web&gt;
&lt;customErrors mode=&quot;RemoteOnly&quot; defaultRedirect=&quot;mycustompage.htm&quot;/&gt;
&lt;/system.web&gt;
&lt;/configuration&gt;</pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。 Web服务返回错误,该格式为HTML格式。我在服务服务器端解决了这个问题。