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

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

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

https://img2.mukewang.com/64f98f4b0001c96409370456.jpg

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

我们正在使用 .Net Core 3.1 和 @microsoft/signalr 3.1.10。


喵喵时光机
浏览 81回答 1
1回答

aluckdog

根据GitHub上的aspnetcore/SignalR服务器端代码,看来调用错误确实是通过字符串值传递的。负责发送错误的方法定义如下:private async Task SendInvocationError(string invocationId, HubConnectionContext connection, string errorMessage){    if (string.IsNullOrEmpty(invocationId))    {        return;    }    await connection.WriteAsync(CompletionMessage.WithError(invocationId, errorMessage));}以及一些关于如何调用它的示例: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;}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。另一方面,客户端 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做法是合理的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript