处理业务逻辑中的sql异常

时间:2016-07-12 14:40:58

标签: c# model-view-controller elmah

我在数据访问层中有executetenonquery方法。当executetenonquery失败时,我需要在Business逻辑中处理异常。 我在BLL中使用Elmah记录器。 ExecuteNonQuery方法没有返回值, 那么我应该在BLL中检查什么条件以记录任何异常被抛出

BLL:

//构造函数

public FormService(ISettings settings, ILogger logger, IFormDataServiceWorker formDataService)
            : base(settings, logger)
        {
            this._formDataService = formDataService;
        } 
        //method calling DAL
        public string GetRefNo(FormData formData)
        {
                foreach (var formFieldData in formFieldDataList)
                {
                    this._formDataService.SubmitFormData(formFieldData);
                }
}

DAL实施:

public void SubmitFormData(FormFieldDTO formFieldData)
        {
            using (var sqlConn = new SqlConnection(Configuration.DBConnection))
            {
                sqlConn.Open();
                using (var sqlcmd = new SqlCommand("usp_SubmissionDataInsert", sqlConn))
                {
                    sqlcmd.CommandType = CommandType.StoredProcedure;
                    sqlcmd.Parameters.Add("@SubmissionId", SqlDbType.UniqueIdentifier).Value = formFieldData.SubmissionId;
                    sqlcmd.Parameters.Add("@FieldId", SqlDbType.SmallInt).Value = formFieldData.FieldId;
                    sqlcmd.Parameters.Add("@FieldTitle", SqlDbType.VarChar, 500).Value = formFieldData.FieldTitle;
                    sqlcmd.Parameters.Add("@FieldData", SqlDbType.VarChar, -1).Value = formFieldData.FieldValue;
                    sqlcmd.Parameters.Add("@FieldName", SqlDbType.VarChar, 200).Value = formFieldData.FieldName; 

                    sqlcmd.ExecuteNonQuery();
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

如果要在业务层中捕获此异常,可以使用try / catch和专门的异常。像这样:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:res="http://resource.webservice.correios.com.br/">
  <soapenv:Header />
  <soapenv:Body>
    <res:buscaEventos xmlns:res="http://schemas.xmlsoap.org/soap/envelope/">
      <usuario>ETC</usuario>
      <senha>SRO</senha>
      <tipo>L</tipo>
      <resultado>T</resultado>
      <lingua>101</lingua>
      <objetos>JS331400752BR</objetos>
    </res:buscaEventos>
  </soapenv:Body>
</soapenv:Envelope>

并且在您的DAL实现中,当发生任何Ado.net异常时,您将抛出此异常类型。

XmlNode eventosNode = xmlDoc.CreateElement 
( "res " , " buscaEventos " " http://schemas.xmlsoap.org/soap/envelope/ " ) ;

所以在你的BLL中你将能够捕捉到这种类型的异常:

public class MyDatabaseLevelException : Exception

说,我认为应该在数据库层(DAL)上记录数据库级异常。因此,在您的情况下,实现此目的的最合适方法是在throw new MyDatabaseLevelException("message", inner); 方法中记录public string GetRefNo(FormData formData) { foreach (var formFieldData in formFieldDataList) { try { this._formDataService.SubmitFormData(formFieldData); } catch (MyDatabaseLevelException exception) { //log or do something with this. } } } 个例外。业务层不应该知道如何处理数据库问题。