这是使用异常的正确方法吗? [英] Is this a proper way to use exceptions?

查看:178
本文介绍了这是使用异常的正确方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个会员资格例外,如下所示:

I have a Membership exception which looks like this:

public enum MembershipError
{
    EmailNotFound,
    EmailNotConfirmed,
    IncorrectPassword,
    EmailExists
}

public class MembershipException : ApplicationException
{
    public MembershipError MembershipError { get; set; }

    public MembershipException(MembershipError membershipError)
        : base(Enum.GetName(typeof (MembershipError), membershipError))
    {
        MembershipError = membershipError;
    }
}

我应该在我的异常中使用枚举,每个枚举的例外?因为那时候我会抓住这样的异常的逻辑:

Should I use an enum in my exception or make an exception for each enum? Because then I would be putting logic when catching the exception like this:

try
{

}
catch (MembershipException exception)
{
    switch (exception.MembershipError)
    {
        case MembershipError.EmailExists:

            break;
            //etc.
    }
}

我的服务层抛出了这些异常,Web层/在动作捕获这些,生成正确的json并返回到视图。
建议一个替代方案?

My service layer throws these exceptions, the web layer/in the action catches these, generate the proper json and return it to the view. Suggest an alternative please?

推荐答案

异常只能用于异常情况。枚举中列出的错误似乎相当标准,我会选择不通过异常来表达。相反,我比较喜欢 TryXXX style API。

Exceptions should only be used for exceptional situations. The errors listed in your enumeration appear to be fairly standard and I would choose not to express them through an exception. Instead I would prefer TryXXX style API over exceptions.

例如

public bool TryGetMembershipData(
  string user, 
  out Data data, 
  out MemberShipError error) {
  ...
}

这篇关于这是使用异常的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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