This question already has an answer here:
ASP.NET - displaying business layer errors in the presentation layer
(1个答案)
7年前关闭。
在我的应用程序中,当发生异常时,我需要从业务层传递错误代码
我需要根据错误代码转到Presentation层,以显示数据库中可用的消息。
我想知道如何从BL传递错误代码并在表示层中获取错误代码。
为了记录异常,我正在使用log4net和企业库4.0。
提前致谢
您也可以使用枚举或常量。我不知道您的ErrorCode类型。
在业务层中,可以通过以下方式引发异常:
因此,在表示层之后,您可以捕获此异常并根据需要对其进行处理。
(1个答案)
7年前关闭。
在我的应用程序中,当发生异常时,我需要从业务层传递错误代码
我需要根据错误代码转到Presentation层,以显示数据库中可用的消息。
我想知道如何从BL传递错误代码并在表示层中获取错误代码。
为了记录异常,我正在使用log4net和企业库4.0。
提前致谢
最佳答案
您可以创建继承自Exception
的自己的业务异常,并使该类接受您的错误代码。此类是业务异常(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);
}
}
关于c# - 从C#中的异常传递错误代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16230573/