首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何识别JavaScript客户端上的SignalR核心集线器错误?

如何识别JavaScript客户端上的SignalR核心集线器错误?
EN

Stack Overflow用户
提问于 2020-11-25 17:46:31
回答 1查看 312关注 0票数 3

我们正在尝试从JavaScript客户端在SignalR核心调用方法上设置错误处理,该客户端需要识别错误的类型并采取相应的操作(例如,如果是授权错误,则应提示用户登录,等等)。

我们已经确定从集线器返回的错误包含一条消息和一个堆栈属性,并构建了以下代码来根据消息属性中包含的文本设置错误代码:

错误文本是否总是以英语返回(因此可以用来识别错误)?或者有没有更好的方法来实现这一点?

我们使用的是.Net核心3.1和@microsoft/signalr 3.1.10。

EN

回答 1

Stack Overflow用户

发布于 2020-12-16 17:17:08

根据GitHub上的aspnetcore/SignalR server-side code,似乎调用错误确实是通过字符串值传递的。

负责发回错误的方法定义如下:

代码语言:javascript
运行
复制
private async Task SendInvocationError(string invocationId, HubConnectionContext connection, string errorMessage)
{
    if (string.IsNullOrEmpty(invocationId))
    {
        return;
    }

    await connection.WriteAsync(CompletionMessage.WithError(invocationId, errorMessage));
}

下面是一些关于如何调用它的示例:

代码语言:javascript
运行
复制
if (!await IsHubMethodAuthorized(scope.ServiceProvider, connection, descriptor, hubMethodInvocationMessage.Arguments, hub))
{
    Log.HubMethodNotAuthorized(_logger, hubMethodInvocationMessage.Target);
    await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
        $"Failed to invoke '{hubMethodInvocationMessage.Target}' because user is unauthorized");
    return;
}
代码语言:javascript
运行
复制
var errorMessage = ErrorMessageHelper.BuildErrorMessage($"Failed to invoke '{bindingFailureMessage.Target}' due to an error on the server.",
    bindingFailureMessage.BindingFailure.SourceException, _enableDetailedErrors);
return SendInvocationError(bindingFailureMessage.InvocationId, connection, errorMessage);

关于错误的唯一信息是errorMessage的字符串参数。

另一方面,client-side javascript library source code

代码语言:javascript
运行
复制
HubConnection.prototype.connectionClosed = function (error) {
    this.logger.log(_ILogger__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].Debug, "HubConnection.connectionClosed(" + error + ") called while in state " + this.connectionState + ".");
    // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
    this.stopDuringStartError = this.stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete.");
    // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
    // If it has already completed, this should just noop.
    if (this.handshakeResolver) {
        this.handshakeResolver();
    }
    this.cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
    
    ...
};

这表明当服务器没有提供任何错误消息时,"Invocation canceled due to the underlying connection being closed."是默认的错误消息。

因此,我相信如果SignalR团队没有改变错误消息发送机制,您的string.includes方法是合理的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65002114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档