ハブでは普通にエラー処理するのと変わらずいけると思います。
一点、HubExceptionと他Exceptionの使い分けがいまいちわかっていません。。
クライアントでの呼び出し側でもfail()かthen()でエラー処理を記述するので問題ないかと。
サーバー側(ハブ)
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string[] Attributes { get; set; }
}
public class HogeHub : Hub
{
public HogeHub()
{
}
public Task<string> GetHubDescription()
{
return Task.Run<string>(async () =>
{
await Task.Delay(3000);
return "ほげげ";
});
}
public Task<Person> GetPerson(string id)
{
var tcs = new TaskCompletionSource<Person>();
var rnd = new Random();
Task.Run(() =>
{
try
{
var num = rnd.Next(100);
if (num % 7 == 0)
{
tcs.SetCanceled();
}
else if (num % 3 == 0)
{
throw new HubException("エラーが発生しました!!!!");
}
else
{
tcs.SetResult(new Person()
{
Id = id,
Name = string.Format("山田太郎{0:00000}", id),
Attributes = Enumerable.Range(1, 10).Select<int, string>((i) => { return string.Format("属性{0:00000}", i); }).ToArray(),
Age = 30
});
}
}
catch(Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
public Task ThrowError()
{
return Task.Run(() =>
{
throw new Exception("何らかのエラーが発生しましたYO");
});
}
}
クライアント
エラーボタン(ID:error-button)、ほげボタン(ID:hoge-button)ページに対するスクリプトコード
/// <reference path="Scripts/typings/jquery/jquery.d.ts" />
/// <reference path="Scripts/typings/signalr/signalr.d.ts" />
$(() => {
var connection = $.hubConnection(<ハブURL>, true);
var hub = connection.createHubProxy("hogeHub");
$("#error-button").click(() => {
hub.invoke("throwError").then(
() => {
console.log("throwError() 成功");
},
(reasons) => {
console.dir(reasons);
});
});
$("#hoge-button").click(() => {
hub.invoke("getPerson", 10).then(
(person) => {
console.log("getPerson() 成功");
console.dir(person);
},
(reasons) => {
console.dir(reasons);
});
});
connection.start().then(
() => {
console.log("[" + new Date() + "] 開始");
hub.invoke("getHubDescription").then(
(result) => {
console.log("[" + new Date() + "] 応答:" + result);
},
(reasons) => {
console.dir(reasons);
});
},
(reasons) => {
console.dir(reasons);
});
});