Лучший код обработчика ошибок для отладки связанных с БД методов в C #? - PullRequest
0 голосов
/ 06 мая 2009

все. У меня есть следующий регион, который я продолжаю отрывать после блоков try {}. Его целью является предоставление отладочной информации всякий раз, когда она настроена обратно в базу данных ... Она хорошо отлаживается (не все, что предполагается отлаживать, но достаточно, чтобы найти именно ошибку, НО ..

Код пахнет. Даже я могу получить это. У вас есть лучшее представление об обработке ошибок для методов БД (я сейчас работаю над реализацией log4net)

Вот код:

регион CatchExceptionsAdv5NoReturnAtAll

    catch (NullReferenceException nre)
    {
        if (userObj == null)
        {
            userObj = new FB.User ();
            FB.User.GiveDefaultUser ( ref userObj );
        }

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
            encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += nre.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
            userObj.Mc.Msg = "Failed to debug application error at " + methodName;
            //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

    } //eof catch

    catch (System.InvalidOperationException ioe) //comm -- occurs when no result set was found !!!
    {
        if (userObj == null)
        {
            userObj = new FB.User ();
            FB.User.GiveDefaultUser ( ref userObj );
        }

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
            encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ioe.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
            userObj.Mc.Msg = "Failed to debug application error at " + methodName;
            //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

    } //eof catch (System.InvalidOperationException)

    catch (System.IndexOutOfRangeException ioore) //comm -- occurs when no result set was found !!!
    {
        if (userObj == null)
        {
            userObj = new FB.User ();
            FB.User.GiveDefaultUser ( ref userObj );
        }

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
            encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ioore.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
            userObj.Mc.Msg = "Failed to debug application error at " + methodName;
            //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

    } //eof catch (System.IndexOutOfRangeException)

    catch (System.Data.SqlClient.SqlException sqle)
    {
        if (userObj == null)
        {
            userObj = new FB.User ();
            FB.User.GiveDefaultUser ( ref userObj );
        }

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
            encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += sqle.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
            userObj.Mc.Msg = "Failed to debug application error at " + methodName;
            //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

    } //eof catch

    catch (System.FormatException fe)
    {
        if (userObj == null)
        {
            userObj = new FB.User ();
            FB.User.GiveDefaultUser ( ref userObj );
        }

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
            encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += fe.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
            userObj.Mc.Msg = "Failed to debug application error at " + methodName;
            //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

    } //eof catch

    catch (Exception ex)
    {
        if (userObj == null)
        {
            userObj = new FB.User ();
            FB.User.GiveDefaultUser ( ref userObj );
        }

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
            encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
            userObj.Mc.Msg = "Failed to debug application error at " + methodName;
            //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

    } //eof catch
    #endregion CatchExceptionsAdv5NoReturnAtAll

Ответы [ 2 ]

2 голосов
/ 06 мая 2009

Обратите внимание на блок обработки исключений в Enterprise Library . Это позволит вам делать то, что вы хотите, не повторяя такие большие блоки кода. Но, в общем, почему бы не выделить весь повторяющийся код, который у вас есть, для каждого исключения. Как минимум, если вы не хотите использовать EntLib, выделите весь повторяющийся код и создайте себе библиотеку методов, которые вы можете безошибочно вызывать из блоков обработки исключений, чтобы делать то, что вы хотите.

0 голосов
/ 06 мая 2009

Я уверен, что реальным ответом было бы использование Enterprise Library или log4net ... Между тем, быстрый и грязный способ рефакторинга состоял в том, чтобы заменить регион следующим вызовом:

  catch (Exception ex)
  {
    System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
    Utils.ErrorHandler.Trap ( ref userObj, st, ex );
    return false;
  } //eof catch

, который указывал на класс обработчика ошибок, представленный ниже, который не улучшает отчеты об ошибках и не обеспечивает лучшую архитектуру для отчетов об ошибках ... пока он просто удалил дублированный код и улучшил читаемость:

using System;

namespace Utils
{
  public class ErrorHandler
  {


    public static void Trap ( ref FB.User userObj, System.Diagnostics.StackTrace st, Exception ex )
    {
      if (userObj == null)
      {
        userObj = new FB.User ();
        FB.User.GiveDefaultUser ( ref userObj );
      }


      if (ex is NullReferenceException)
      {
        if (userObj == null)
        {
          userObj = new FB.User ();
          FB.User.GiveDefaultUser ( ref userObj );
        }


        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
          encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
          userObj.Mc.Msg = "Failed to debug application error at " + methodName;
          //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

      } //eof if

      if (ex is System.InvalidOperationException) //comm -- occurs when no result set was found !!!
      {
        if (userObj == null)
        {
          userObj = new FB.User ();
          FB.User.GiveDefaultUser ( ref userObj );
        }


        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
          encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
          userObj.Mc.Msg = "Failed to debug application error at " + methodName;
          //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

      } //eof if

      if (ex is System.IndexOutOfRangeException) //comm -- occurs when no result set was found !!!
      {
        if (userObj == null)
        {
          userObj = new FB.User ();
          FB.User.GiveDefaultUser ( ref userObj );
        }


        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
          encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
          userObj.Mc.Msg = "Failed to debug application error at " + methodName;
          //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

      } //eof if

      if (ex is System.Data.SqlClient.SqlException)
      {
        if (userObj == null)
        {
          userObj = new FB.User ();
          FB.User.GiveDefaultUser ( ref userObj );
        }


        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
          encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
          userObj.Mc.Msg = "Failed to debug application error at " + methodName;
          //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

      } //eof if

      if (ex is System.FormatException)
      {
        if (userObj == null)
        {
          userObj = new FB.User ();
          FB.User.GiveDefaultUser ( ref userObj );
        }


        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
          encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
          userObj.Mc.Msg = "Failed to debug application error at " + methodName;
          //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

      } //eof if

      if (ex is Exception)
      {
        if (userObj == null)
        {
          userObj = new FB.User ();
          FB.User.GiveDefaultUser ( ref userObj );
        }


        string methodName = st.GetFrame ( 1 ).GetMethod ().Name;
        string className = st.GetFrame ( 1 ).GetFileName ();
        int lineNumber = st.GetFrame ( 1 ).GetFileLineNumber ();

        string encryptedErrorCode = String.Empty;
        encryptedErrorCode += "className - " + className + " methodName ";
        encryptedErrorCode += methodName + " lineNumber " + lineNumber.ToString ();
        encryptedErrorCode += userObj.DomainName;

        if (System.Convert.ToInt16 ( BL.Conf.Instance.Vars["EncryptErrorMessages"] ) == 1)
          encryptedErrorCode = Utils.DataEncryption.EncryptString ( encryptedErrorCode, userObj.DomainName );


        userObj.Mc.Msg = "An error in the application occurred. Report the following error code " + encryptedErrorCode;
        userObj.Mc.ClassName += className + " ; ";
        userObj.Mc.MethodName += methodName + " ; ";
        userObj.Mc.DebugMsg += ex.Message;
        //
        if (Providers.nsDbMeta.DbDebugger.DebugAppError ( ref userObj ) == false)
        {
          userObj.Mc.Msg = "Failed to debug application error at " + methodName;
          //Providers.nsDbMeta.Providers.nsDbMeta.DbDebugger.WriteIf ( userObj.Mc.Msg );
        }

      } //eof catch


    } //eof method 



  }//eof class CustomException
} //eof namespace U
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...