开发者

Which exception should be thrown?

I wrote a custom action method selector attribute that has three bool properties. It's invalid for all three of them to be false. At least one of them has to be true. When IsValidForRequest gets executed I check that at least one of them is true. But if none is, which exception should I throw?

Some relevant code:

public class MyCustomAttribute : ActionMethodSelectorAttribute
{
    public bool Prop1 { get; set; }
    public bool Prop2 { get; set; }
    public bool Prop3 { get; set; }

    public MyCustomAttribute()
    {
        this.Prop1 = true;
        this.Prop2 = true;
        this.Prop3 = true;
    }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        // at least one of them must be true
        if (!this.Prop1 && !this.Prop2 && !this.Prop3)
        {
            throw new ?????
        }

        // other codez he开发者_如何学运维re
    }
}

Attributes have this nice ability of initializing them while also providing property values, so I have to check them in the IsValidForRequest method.

[MyCustom(Prop1 = false, Prop2 = false, Prop3 = false)]

Which exception should be thrown?


I'd probably throw InvalidOperationException, because the operation is not valid for the object's current state.


You could try with ArgumentException if those properties got loaded from user input... or you could implement your own custom exception to throw.

It really depends on how those properties got set.


Throw an exception with your specific custom message using

throw new Exception("Custom Error Message");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜