错误处理程序在客户端添加如下:
$.connection.hub.url = "/signalr";
$.connection.hub.logging = true;
$.connection.hub.error(function(error) {
console.log('SignalrAdapter: ' + error);
});
$.connection.hub.start().done(function() { me.onStartDone(); });
// ...
在服务器上它是:
hubConfiguration.EnableDetailedErrors = true;
相对于the docs,这应该足够了。
在我的例外情况下抛出它只显示它的日志文本而不调用处理程序:
[18:18:19 GMT+0000()] SignalR: ... [[[my error description here]]] ...
在我的cshtml页面:
<script src="~/Scripts/vendor/jquery.signalR-2.1.2.js"></script>
<script src="~/signalr/hubs"></script>
但是,如果我将错误处理程序附加到方法本身,则会调用它:
$.connection.operatorHub.server.myMethodName(someParam).fail(function(error) {
console.log("Error handler called: " + error);
});
如何处理一般错误?
更新。 答案如下。另见:
希望它有所帮助。
答案 0 :(得分:11)
我在一个小聊天项目(downloaded here)上测试过,这个方法似乎只处理连接错误。
$.connection.hub.error(function(error) {
console.log('SignalrAdapter: ' + error);
});
我能够处理HubPipelineModule
类的所有异常。
1)我创建了SOHubPipelineModule
public class SOHubPipelineModule : HubPipelineModule
{
protected override void OnIncomingError(ExceptionContext exceptionContext,
IHubIncomingInvokerContext invokerContext)
{
dynamic caller = invokerContext.Hub.Clients.Caller;
caller.ExceptionHandler(exceptionContext.Error.Message);
}
}
2)我将模块添加到GlobalHost.HubPipeline
// Any connection or hub wire up and configuration should go here
GlobalHost.HubPipeline.AddModule(new SOHubPipelineModule());
var hubConfiguration = new HubConfiguration { EnableDetailedErrors = true };
app.MapSignalR(hubConfiguration);
3)我的ChatHub
课程:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
throw new Exception("exception for Artyom");
Clients.All.broadcastMessage(name, message);
}
}
4)在js中,我使用此代码来获取异常消息:
$.connection.chatHub.client.exceptionHandler = function (error) {
console.log('SignalrAdapter: ' + error);
alert('SignalrAdapter: ' + error);
};
答案 1 :(得分:6)
我在客户端上使用了错误处理,如下所示:
适用于SignalR版本2
更多细节:SignalR documentation - How to handle errors in the Hub class
Hub - AppHub.cs:
.flexible{display: flex; flex-direction: row;}
#form1:hover{
width: 100%;
}
#form2:hover{
width: 100%;
}
客户端:
public class AppHub : Hub
{
public void Send(string message)
{
throw new HubException("Unauthorized", new { status = "401" });
}
}