c# - 使用自定义异常返回信息 C#

标签 c# exception custom-exceptions

我有以下问题:

  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 只是检查员工是否可以获得工资的方法之一(因此雇主不支付工资可能还有其他原因)。对于每个原因,我都想抛出一个带有适当信息的异常:所需的工作时间、实际工作时间等。

问题是:

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

最佳答案

避免使用控制流异常

这是.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..

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

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;
}

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

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

public interface IPayment
{
    void Pay();
}

为每种情况实现接口(interface)

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();

关于c# - 使用自定义异常返回信息 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39808813/

相关文章:

c# - 当我在 sql 查询中使用 go 语句时,Oledb 连接出现错误

java - 强制重写类时调用基类版本方法,否则抛出异常

c++ - 浮点 NaN 取决于 C++ 中不相关的异常处理

c# - 在保留堆栈跟踪和内部异常信息的同时抛出新异常

java - 自定义异常(RuntimeException)

mule - 如何处理 MULE 中的未检查/运行时异常?

c# - 更新二进制文件信息

c# - BackgroundWorker() 运行时 UI 挂起

c# - 使用最小起订量的同步方法测试 EF 异步方法

delphi - 使用非应用程序文件夹中的 DLL 时,函数中会引发外部异常