调用.fail(error)而不引发异常 [英] Call .fail(error) without throwing exception

查看:150
本文介绍了调用.fail(error)而不引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SignalR,有可能在返回特定值时调用 .fail 而不是 .done 。中心方法?

Using SignalR, is there any possibility to call .fail instead of .done when specific values are returned by hub method?

也许使用SignalR管道吗?

Perhaps using the SignalR pipeline?

public bool Delete(int addressId)
{
    // User should not be able to delete default address
    if(AddressService.IsDefaultAddressOfCustomer(addressId))
        return false; // Should call .fail() on client

    AddressService.Delete(addressId);
    return true; // Should call .done() on client
}

另一种方法是抛出例外,但我想避免这种情况,因为错误实际上不是服务器故障,而是用户故障。

The alternative would be to throw an exception but I would like to avoid that since the error is not really a server fault, but a user fault.

推荐答案

假设您真的确信异常不是适合您的工具,您可以使用定义的一些自定义属性来标记必须将返回值 false 转换为错误的方法。 ,然后使用 HubPipelineModule 中的 BuildIncoming 拦截所有来电:

Assuming you are really convinced an exception is not the right tool for you, you could use some custom attribute you would define to mark methods where a false return value must be translated into an error, and then intercept any incoming call with BuildIncoming from HubPipelineModule:

http://msdn.microsoft.com/zh-CN/library/microsoft.aspnet.signalr.hubs.hubpipelinemodule.buildincoming(v = vs.118).aspx

从内部可以拦截对原始方法的调用,检查其是否标记有您的属性te,如果返回 false ,则可以从那里抛出异常。最重要的是,您仍然会抛出一个异常以使其调用 .fail()客户端,但是该异常不会使您的业务逻辑肿。这样的事情:

From inside there you can intercept the call to your original method, inspect if it's marked with your attribute and if it returned false, if it's the case you can throw an exception from there. The bottom line is, you would still throw an exception to make it call .fail() client-side, but that exception would not bloat your business logic. Something like this:

public class FailPipelineModule : HubPipelineModule
{
    public override Func<IHubIncomingInvokerContext, Task<object>> BuildIncoming(Func<IHubIncomingInvokerContext, Task<object>> invoke)
    {
        return base.BuildIncoming(context =>
        {
            var r = (bool)(invoke(context)).Result;
            if (context.MethodDescriptor.Attributes.Any(a => typeof(FailAttribute) == a.GetType()) && !r)
                throw new ApplicationException("false");
            return Task.FromResult((object)r);
        });
    }
}

您需要定义 FailAttribute ,用它标记集线器的方法并在启动时注册 FailPipelineModule

You'll need to define FailAttribute, use it to mark your hub's method and register FailPipelineModule at startup.

这篇关于调用.fail(error)而不引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆