2

在我的应用程序中,当发生异常时,我需要根据错误代码将错误代码从业务层传递到表示层,我需要显示数据库中可用的消息。
我想知道如何从 BL 传递错误代码并在表示层中获取错误代码。
对于记录异常,我使用 log4net 和 Enterprise library 4.0。

提前致谢

4

1 回答 1

1

您可以创建自己的继承自 的业务异常Exception,并使该类接受您的错误代码。此类将成为您域的一部分,因为它是一个业务例外。与数据库异常等基础设施异常无关。

public class BusinessException : Exception
{
  public int ErrorCode {get; private set;}

  public BusinessException(int errorCode)
  {
     ErrorCode = errorCode;
  }
}

您还可以使用枚举或常量。我不知道您的 ErrorCode 类型。

在您的业务层中,您可以通过以下方式抛出异常:

throw new BusinessException(10);  //If you are using int
throw new BusinessException(ErrorCodes.Invalid); //If you are using Enums
throw new BusinessException("ERROR_INVALID"); //

因此,在您的表示层之后,您可以捕获此异常并根据需要对其进行处理。

public void PresentationMethod()
{
   try
   {
      _bll.BusinessMethod();
   }
   catch(BusinessException be)
   {
      var errorMessage = GetErrorMessage(be.ErrorCode);
      ShowErrorUI(errorMessage);
   }
}
于 2013-04-26T07:33:03.427 回答