我们正在尝试从JavaScript客户端在SignalR核心调用方法上设置错误处理,该客户端需要识别错误的类型并采取相应的操作(例如,如果是授权错误,则应提示用户登录,等等)。
我们已经确定从集线器返回的错误包含一条消息和一个堆栈属性,并构建了以下代码来根据消息属性中包含的文本设置错误代码:
错误文本是否总是以英语返回(因此可以用来识别错误)?或者有没有更好的方法来实现这一点?
我们使用的是.Net核心3.1和@microsoft/signalr 3.1.10。
发布于 2020-12-16 17:17:08
根据GitHub上的aspnetcore/SignalR server-side code,似乎调用错误确实是通过字符串值传递的。
负责发回错误的方法定义如下:
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
的字符串参数。
另一方面,client-side javascript library source code
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
方法是合理的。
https://stackoverflow.com/questions/65002114
复制相似问题