Return 包含自定义异常 C# 的信息

Return information with Custom Exceptions C#

我遇到以下问题:

  1. 我有服务方法:

    public bool EmployeeCanReiceivePayment(int employeeId)
    {
       ...
    
       int workingHours = this.GetEmployeeWorkingHours(employeeId);
    
       if(workingHours < N)
       {
         throw new EmployeeCannotReceivePaymentException();
       }
    
       return true;
    }
    
     public int GetEmployeeWorkingHours(int employeeId)
    {
      //returns the number of working hours of the employee for the last month
    }
    

GetEmployeeWorkingHours 只是检查员工是否可以领取工资的方法之一(因此雇主可能有其他原因不支付)。对于这些原因中的每一个,我都想抛出一个异常并提供适当的信息:所需工作时间、实际工作时间等。

问题是:

有没有办法 return 对象或附加信息与我的自定义异常。我所说的附加信息是指一个对象或几个参数。

我同意其他人在这里所说的,通过例外情况强制执行您的 BL 不是一个好的做法。您可以 return 包含成功状态 + 详细信息和有效 return 数据的 "ResultObject" 而不是异常。

但是,如果您确实选择这样做,那么请自定义您的自定义异常以包含不仅仅是默认构造函数。他们和其他人一样 class。类似于:

public class MyCustomException : Exception
{
   //This is like you have now
   public MyCustomException() { }

   //This is if you want to have different messages
   public MyCustomException(string message)  : base(message{ }

   //This is if you want to have different data to add (don't use object but a custom type
   public MyCustomException(object yourObject)
   {
      YourObject = yourObject;
   }

   public object YourObject { get; set; }
}

在你的场景中可能是这样的:

public class EmployeeException : Exception { ... }
//Add what you need from the example above

//Then when needed:
new EmployeeException("some text for this error");
new EmployeeException("some other text for this error");

//Or when with a proper object to describe more details:
new EmployeeException(new NotEnoughHours { ... });

避免对控制流使用异常

这是 .NET Framework 的使用规则

DA0007: Avoid using exceptions for control flow

The use of exception handler as part of the regular program execution logic can be expensive and should be avoided. In most cases, exceptions should be used only for circumstances that occur infrequently and are not expected..

创建一个包含所有需要信息的 class 而不是抛出异常。

public class PaymentValidation
{
    public bool IsValid { get; set;}

    public YourType SomeAdditionalInformation { get; set;}
}

public PaymentValidation EmployeeCanReiceivePayment(int employeeId)
{
    int workingHours = this.GetEmployeeWorkingHours(employeeId);

    var validationResult = new PaymentValidation();
    validationResult.IsValid = true;

    if(workingHours < N)
    {
        validationResult.IsValid = false;
    }

    return validationResult;
}

返回自己的类型将为进一步更改提供更多可能性。

例如创建一个表示返回类型的接口。并为您拥有的每个案例创建自己的实现

public interface IPayment
{
    void Pay();
}

针对每种情况实施接口

public class NotEnoughWorkingHoursPayment : IPayment
{
    public void Pay()
    {
        //Do nothing or log failed payment or inform user about it
    }
}

public class SuccesfullPayment : IPayment
{
    public void Pay()
    {
        //Execute payment
    }
}


public class PaymentService
{
    public IPayment ValidatePayment()
    {
        const int MIN_WORKING_HOURS = 40;
        int workingHours = this.GetEmployeeWorkingHours(employeeId);

        if(workingHourse < MIN_WORKING_HOURS)
        {
            return New NotEnoughWorkingHoursPayment();
        }

        return new SuccesfullPayment();
    }
}

那么使用起来就会非常简单易懂

IPayment payment = paymentService.ValidatePayment();

payment.Pay();