我希望能够自定义在服务器上发生异常时传递给客户端的错误对象.
我在客户端上使用'then'函数来处理成功和失败:
hub.server.login(username, password).then(function(result) {
// use 'result'
}, function(error) {
// use 'error'
});
Run Code Online (Sandbox Code Playgroud)
如果登录成功,则"result"是服务器上Login方法的返回值.如果登录失败,我抛出'CustomException'的异常.这是"Code"属性的例外.
if (!IsValidLogin(username, password))
throw new CustomException { Code: "BADLOGIN", Message: "Invalid login details" };
Run Code Online (Sandbox Code Playgroud)
如果我启用了详细的异常,则客户端上的"错误"参数是"无效的登录详细信息" - 异常的Message属性.
有没有什么办法可以有选择地将错误结果从字符串更改为复杂对象?即如果在hub方法中抛出'CustomException',则返回客户端失败处理程序的{Code:[...],Message:[...]}对象?
这应该证明我希望在客户端看到的内容:
hub.server.login(username, password).then(function(userInfo) {
alert("Hello " + userInfo.Name);
}, function(err) {
if (err.Code === "BADLOGIN.USERNAME")
alert("Unrecognised user name");
else if (err.Code === "BADLOGIN.PASSWORD");
alert("Invalid password");
else
alert("Unknown error: " + err.Message);
});
Run Code Online (Sandbox Code Playgroud)
(注意'错误'上的'代码'和'消息'属性).
当您调用 MapHubs 并将 EnabledDetailedErrors 设置为 true 时,如下所示:
RouteTable.Routes.MapHubs(new HubConfiguration { EnableDetailedErrors = true });
Run Code Online (Sandbox Code Playgroud)
您将收到异常的消息字符串作为失败处理程序的参数。
我发现您已经弄清楚了这一点,但我添加了服务器端代码,以便为以后可能发现此问题的其他人启用详细错误。
不幸的是,没有简单的方法可以将复杂的对象发送到失败处理程序。
不过你可以这样做:
if (!IsValidUsername(username))
{
var customEx = new CustomException { Code: "BADLOGIN.USERNAME", Message: "Invalid login details" };
throw new Exception(JsonConvert.SerializeObject(customEx));
}
if (!IsValidPassword(username, password))
{
var customEx = new CustomException { Code: "BADLOGIN.PASSWORD", Message: "Invalid login details" };
throw new Exception(JsonConvert.SerializeObject(customEx));
}
Run Code Online (Sandbox Code Playgroud)
然后在客户端:
hub.server.login(username, password).then(function(userInfo) {
alert("Hello " + userInfo.Name);
}, function(errJson) {
var err = JSON.parse(errJson);
if (err.Code === "BADLOGIN.USERNAME")
alert("Unrecognised user name");
else if (err.Code === "BADLOGIN.PASSWORD");
alert("Invalid password");
else
alert("Unknown error: " + err.Message);
});
Run Code Online (Sandbox Code Playgroud)
我知道这很丑陋,但它应该有效。