在设计数据层或任何其他分层架构

在设计数据层或任何其他分层架构

本文介绍了如何异常的处理方式,在设计数据层或任何其他分层架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造,我要处理,应该由业务层异常的来源明确的想法逮住异常的数据访问层。
我做这样的东西..

I am creating a data access layer where I want to handle exceptions that should be catched by Business layer with clear idea of the source of exception.I am doing something like this..

修改

private void OpenConnection()
        {
                if (ConnectionState.Closed == _connection.State)
                    _connection.Open();
        }

在上面给出的code我知道的异常原因。而想要把它扔在BL处理显示信息。

In the above given code i know an reason for exception. And want to throw it to be handled at BL to display message.

不过,我正在使用DL此功能只与codeS一些其他线路。

But I am using this function in DL only with some other line of codes.

protected DataTable GetDataTable(string Query)
 {
     DataTable dt =new DataTable();
     SqlCommand cmd = InitializeCommand(Query);

     SqlDataAdapter adp = new SqlDataAdapter(cmd);
     try
     {
         OpenConnection();
         adp.Fill(dt);
         CloseConnection(true);
         return dt;
     }
     catch (SqlException ex)
     { throw ex; }
     finally
     {
         adp.Dispose();
         cmd.Dispose();
     }
 }

现在,如果在中出现异常OpenConnection的()试图打开连接,然后在该行抛出前应用程序崩溃在OpenConnection的本身,而我希望它回归例外。
我应该如何处理这个问题。
而且延长我的问题在第二个函数 GetDataTable 如果出现异常是什么样的异常应以相同的细节被抛出在这一点上,以及如何发生。
我只知道这种方式,但这是一个弘方式,我认为。

Now if an exception occurs in OpenConnection() while trying to open the connection then the application crashes at the line throw ex in OpenConnection itself while I was expecting it to return exception.How should I handle this issue.Moreover extending my question in the second function GetDataTable if an exception occurs what kind of exception should be thrown with same details as occured at this point and how.I only know this way but this is a wong way i think.

throw new ApplicationException(ex.message,ex.innerexception)

修改

假设连接到服务器losts或我使用错误的连接字符串。现在,我使用BL GetDataTable功能。异常会在哪里发生,我应该在哪里处理呢?
我想知道,在DL发生的问题。考虑到BL不知道DL的code

Suppose Connection to server losts or I am using wrong connection string. Now I use GetDataTable function from BL. Where will exception occur and where should I handle it ?I want to know the problem that occured in DL. Considering BL dont know the code of DL

推荐答案

有几件事情可以做。

您可以根据您的地方有问题,有不同的尝试块,并抛出新的异常:

You can have different try blocks, and throw new exceptions according to where you had the problem:

 try
 {
     OpenConnection();
     adp.Fill(dt);
 }
 catch (SqlException ex)
 { throw new SqlException("Could not open/populate", ex); }
 finally
 {
     adp.Dispose();
     cmd.Dispose();
 }

 try
 {
     CloseConnection(true);
     return dt;
 }
 catch (SqlException ex)
 { throw new SqlException("Could not close connection", ex); }
 finally
 {
     adp.Dispose();
     cmd.Dispose();
 }

这篇关于如何异常的处理方式,在设计数据层或任何其他分层架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:16