How to manipulate SqlException message into user friendly message

后端 未结 1 1623
遇见更好的自我
遇见更好的自我 2020-12-11 08:55

I want to obtain all the replaced values in the following exception from error message obtained on UI to display custom message up to a granular level

相关标签:
1条回答
  • 2020-12-11 09:20

    SQLException has Number property, you can use this number then translate to whatever text you want.

    public static string GetSqlExceptionMessage(int number)
    {
      //set default value which is the generic exception message
      string error = MyConfiguration.Texts.GetString(ExceptionKeys.DalExceptionOccured);   
      switch (number)
      {
        case 4060:
          // Invalid Database
          error = MyConfiguration.Texts.GetString(ExceptionKeys.DalFailedToConnectToTheDB);   
        break;
        case 18456:
          // Login Failed
          error = MyConfiguration.Texts.GetString(ExceptionKeys.DalFailedToLogin);   
        break;
        case 547:
          // ForeignKey Violation
          error = MyConfiguration.Texts.GetString(ExceptionKeys.DalFKViolation);   
        break;
        case 2627:
          // Unique Index/Constriant Violation
          error = MyConfiguration.Texts.GetString(ExceptionKeys.DalUniqueConstraintViolation);
        break;
        case 2601:
          // Unique Index/Constriant Violation
          error =MyConfiguration.Texts.GetString(ExceptionKeys.DalUniqueConstraintViolation);   
        break;
        default:
          // throw a general DAL Exception
          MyConfiguration.Texts.GetString(ExceptionKeys.DalExceptionOccured);   
        break;
      }
    
      return error;
    }
    

    Example code copy from: Get SqlException friendly messages using its Error Number

    0 讨论(0)
提交回复
热议问题