/// <summary> /// Constructor to use. Takes MySqlException to display. /// </summary> /// <param name="e">MySqlException to show.</param> /// <param name="status">Table engine statuses to display in advanced information.</param> public SqlErrorDialog(DbException e, string status) { if (e == null) throw new ArgumentNullException("e"); if (status == null) throw new ArgumentNullException("status"); InitializeComponent(); // Load error icon imageList.Images.Add(SystemIcons.Error); iconLabel.ImageIndex = 0; // Fill text boxes errorText.Text = e.Message; statusText.Text = status; // We try to recognize, if this exception is MySqlException // For this we'll use reflection. We'll try to find property "Number" Type exceptionType = e.GetType(); Debug.Assert(exceptionType != null, "Failed to retrieve type information for exception!"); // Extract property information PropertyInfo numberProperty = exceptionType.GetProperty("Number"); // If there is Number property, extract its value object numberValueObject = null; if (numberProperty != null) { try { // Try to get value of Number property numberValueObject = numberProperty.GetValue(e, null); } catch (Exception ex) { // This is bad, but not fatal - we can show unknown error code Debug.Fail("Failed to get value for Number property!", ex.ToString()); } } else { // This is bad, but not fatal - we can show unknown error code Debug.Fail("Failed to extract Number property description!"); } // If extracted value is not null, convert it to string and append to error label if (numberValueObject != null) errorLabel.Text = String.Format(CultureInfo.CurrentCulture, errorLabel.Text, numberValueObject.ToString()); // If value is null, append unknow error code else errorLabel.Text = String.Format(CultureInfo.CurrentCulture, errorLabel.Text, Resources.UnknownErrorCode); }
/// <summary> /// Classifies the specified <see cref="System.Data.Common.DbException"/>. /// </summary> /// <param name="exception">The exception.</param> /// <returns></returns> public static ExceptionType Classify(DbException exception) { if (exception == null) { return(ExceptionType.Unknown); } var sqlException = exception as SqlException; if (sqlException != null) { return(LookupSqlException(sqlException)); } //reflection works across //System.Data.OracleClient, Oracle.DataAccess.Client (ODP) //also DDTek.Oracle, Devart.Data.Oracle //TODO: reference provider directly. if (exception.GetType().Name.Equals("OracleException", System.StringComparison.OrdinalIgnoreCase)) { var oracleCode = FindCode(exception); return(LookupOracleException(oracleCode)); } if (exception.GetType().Name.Equals("MySqlException", System.StringComparison.OrdinalIgnoreCase)) { return(LookupMySqlException(exception)); } return(ExceptionType.Unknown); }
/* OdbcException, OleDbException, IfxException, Db2Exception, and possible others * have Errors collection which contains fields: NativeError and SQLState * These fields can be extracted using reflection */ public override int ExtractSingleErrorCode(DbException sqle) { System.Type type; PropertyInfo pi; int nativeError; type = sqle.GetType(); pi = type.GetProperty("Errors"); if (pi == null) // there is no Errors property { return(0); } nativeError = 0; foreach (object o in (pi.GetValue(sqle, null) as IEnumerable)) { pi = o.GetType().GetProperty("NativeError"); if (pi == null) { return(0); } nativeError = (int)pi.GetValue(o, null); if (nativeError != 0) { break; } } return(nativeError); }
static void PrintException(DbException ex) { Console.Write(ex.GetType().ToString() + ": " + ex.Message + "\n"); //Console.Write("\t" + "Errors = " + // (ex.Errors != null ? ex.Errors.ToString() : "<null>") + "\n"); Console.Write("\t" + "HelpLink = " + (ex.HelpLink != null ? ex.HelpLink.ToString() : "<null>") + "\n"); Console.Write("\t" + "Source = " + (ex.Source != null ? ex.Source.ToString() : "<null>") + "\n"); Console.Write("\t" + "TargetSite = " + (ex.TargetSite != null ? ex.TargetSite.ToString() : "<null>") + "\n"); #if EDBC #elif SQLSERVER Console.WriteLine(""); Console.Write("\t" + "Class = " + (ex.Class.ToString()) + "\n"); Console.Write("\t" + "Number = " + (ex.Number.ToString()) + "\n"); Console.Write("\t" + "Server = " + (ex.Server != null?ex.Server.ToString():"<null>") + "\n"); Console.Write("\t" + "State = " + (ex.State.ToString()) + "\n"); #elif OLEDB #endif PrintInnerException(ex, 1); Console.WriteLine(""); }
public override string ExtractSingleSqlState(DbException sqle) { System.Type type; PropertyInfo pi; string sqlState; type = sqle.GetType(); pi = type.GetProperty("Errors"); if (pi == null) // there is no Errors property { return(null); } sqlState = ""; foreach (object o in (pi.GetValue(sqle, null) as IEnumerable)) { pi = o.GetType().GetProperty("SQLState"); if (pi == null) { return(null); } sqlState = (string)pi.GetValue(o, null); if (sqlState.Length != 0) { break; } } return(sqlState); }
public Exception Convert(AdoExceptionContextInfo adoExceptionContextInfo) { DbException sqlException = ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException); string message = adoExceptionContextInfo.Message; string sql = adoExceptionContextInfo.Sql; int errorCode = (int)sqlException.GetType().GetProperty("NativeError").GetValue(sqlException, null); if (errorCode >= 1 && errorCode <= 90) { return(new SQLGrammarException(message, sqlException, sql)); } if (integrityViolationCategories.Contains(errorCode)) { string constraintName = extracter.ExtractConstraintName(sqlException); return(new ConstraintViolationException(message, sqlException, sql, constraintName)); } if (connectionCategories.Contains(errorCode)) { return(new ADOConnectionException(message, sqlException, sql)); } if (dataCategories.Contains(errorCode)) { return(new DataException(message, sqlException, sql)); } return(HandledNonSpecificException(sqlException, message, sql)); }
public virtual void Log(DbException e, string sql, DbParameterCollection param) { if (!Sbw.DbClinet.Log.IsDebug) { if (e != null) { throw e; } } else { System.Text.StringBuilder sb = new System.Text.StringBuilder("参数: "); if (param != null && param.Count > 0) { for (int i = 0; i < param.Count; i++) { if (i < param.Count - 1) { sb.AppendFormat("{0} = '{1}',", param[i].ParameterName, param[i].Value); } else { sb.AppendFormat("{0} = '{1}'", param[i].ParameterName, param[i].Value); } } } Sbw.DbClinet.Log.Error("异常类:{0},异常信息:{1},{2}", e.GetType().Name, e.Message, sb.ToString()); } }
public static bool IsCancellationException(DbException exception) { const int CanceledNumber = 0; // fast path using default SqlClient if (exception is SqlException sqlException && sqlException.Number == CanceledNumber) { return(true); } const string AlternateClientSqlExceptionName = #if NETSTANDARD1_3 || NET45 "Microsoft.Data.SqlClient.SqlException"; #else "System.Data.SqlClient.SqlException"; #endif var exceptionType = exception.GetType(); // since SqlException is sealed in both providers (as of 2020-01-26), // we don't need to search up the type hierarchy if (exceptionType.ToString() == AlternateClientSqlExceptionName) { var numberProperty = exceptionType.GetTypeInfo().DeclaredProperties .FirstOrDefault(p => p.Name == nameof(SqlException.Number) && p.CanRead && p.GetMethod.IsPublic && !p.GetMethod.IsStatic); if (numberProperty != null) { return(Equals(numberProperty.GetValue(exception), CanceledNumber)); } } return(false); }
// private static string GetMessage(DbException ex) { // var errors = new StringBuilder(); // errors.AppendLine(); //#if DEBUG // errors.AppendLine($"[{ex.GetType().Name}]"); //#endif // string[] item; // switch (ex.Number) { // case -1: // errors.AppendLine(ExceptionResource.Sql_N1); // break; // case 2: // errors.AppendLine(ExceptionResource.Sql_2); // break; // case 53: // errors.AppendLine(ExceptionResource.Sql_53); // break; // case 201: // item = ex.Message.Split('\''); // errors.AppendLine(string.Format(ExceptionResource.Sql_201, item[1], item[3])); // break; // case 207: // item = ex.Message.Split('\''); // errors.AppendLine(String.Format(ExceptionResource.Sql_207, item[1])); // break; // case 208: // item = ex.Message.Split('\''); // errors.AppendLine(String.Format(ExceptionResource.Sql_208, item[1])); // break; // case 515: // item = ex.Message.Split('\''); // errors.AppendLine(String.Format(ExceptionResource.Sql_515, item[1], item[3])); // break; // case 547: // item = ex.Message.Split(' '); // var parts = ex.Message.Split("'\"".ToCharArray()); // switch (item[1].ToUpper()) { // case "INSERT": // errors.AppendLine(string.Format(ExceptionResource.Sql_547_Insert, parts[1], parts[5], parts[7])); // break; // case "UPDATE": // errors.AppendLine(ExceptionResource.Sql_547_Update); // break; // default: // errors.AppendLine(ExceptionResource.Sql_547_Delete); // break; // } // break; // case 2627: // item = ex.Message.Split("()".ToCharArray()); // errors.AppendLine(String.Format(ExceptionResource.Sql_2627, item[1])); // break; // case 2812: // item = ex.Message.Split('\''); // errors.AppendLine(String.Format(ExceptionResource.Sql_2812, item[1])); // break; // case 3702: // item = ex.Message.Split('"'); // errors.AppendLine(String.Format(ExceptionResource.Sql_3702, item[1])); // break; // case 4060: // // offline // // detach // // invalid name // errors.AppendLine(ExceptionResource.Sql_4060); // break; // case 4121: // item = ex.Message.Split('"'); // errors.AppendLine(String.Format(ExceptionResource.Sql_4121, item[1], item[3])); // break; // case 8114: // item = ex.Message.Split(' '); // errors.AppendLine(String.Format(ExceptionResource.Sql_8114, item[4], item[6].Replace(".", ""))); // break; // case 8144: // item = ex.Message.Split(' '); // errors.AppendLine(String.Format(ExceptionResource.Sql_8144, item[3])); // break; // case 8178: // item = ex.Message.Split('\''); // errors.AppendLine(String.Format("کوئری اجرا شده، شامل پارامتری به نام '{0}' می باشد که به آن ارسال نشده یا مقدار NULL ارسال شده است", item[3])); // break; // case 18456: // item = ex.Message.Split('\''); // errors.AppendLine(String.Format(ExceptionResource.Sql_18456, item[1])); // break; // default: // errors.AppendLine($"{ex.Number}: {ex.Message}"); // break; // } // errors.AppendLine(); // return errors.ToString(); // } // private static string GetMessage(UpdateException ex) { // var errors = new StringBuilder(); // errors.AppendLine(); //#if DEBUG // errors.AppendLine($"[{ex.GetType().Name}]"); //#endif // // Unable to determine the principal end of the 'Psyco.Pishro.Model.AccountTypeCultureModel_Culture' relationship. Multiple added entities may have the same primary key. // if (ex.Message.Contains("Multiple added entities may have the same primary key")) // errors.AppendLine("چندین آیتم با کلید اصلی یکسان به پایگاه داده اضافه شده است"); // // An error occurred while updating the entries. See the inner exception for details. // else if (ex.Message.Contains("An error occurred while updating the entries. See the inner exception for details")) // errors.AppendLine("در زمان بروزرسانی پایگاه داده خطایی رخ داده است"); // else errors.AppendLine($"{ex.GetType().Name}: {ex.Message}"); // errors.AppendLine(); // foreach (var entry in ex.StateEntries) { // var entity = entry.Entity; // if (entity == null) continue; // var entityName = GetEntityName(entity); // errors.AppendLine($"({entityName} دچار مشکل شده است)"); // } // errors.AppendLine(); // return errors.ToString(); // } // private static string GetMessage(DbUpdateException ex) { // var errors = new StringBuilder(); // errors.AppendLine(); //#if DEBUG // errors.AppendLine($"[{ex.GetType().Name}]"); //#endif // // Unable to determine the principal end of the 'Psyco.Pishro.Model.AccountTypeCultureModel_Culture' relationship. Multiple added entities may have the same primary key. // if (ex.Message.Contains("Multiple added entities may have the same primary key")) // errors.AppendLine("چندین آیتم با کلید اصلی یکسان به پایگاه داده اضافه شده است"); // // An error occurred while updating the entries. See the inner exception for details. // else if (ex.Message.Contains("An error occurred while updating the entries. See the inner exception for details")) // errors.AppendLine("در زمان بروزرسانی پایگاه داده خطایی رخ داده است"); // else errors.AppendLine(ex.Message); // errors.AppendLine(); // foreach (var entry in ex.Entries) { // var entity = entry.Entity; // if (entity == null) continue; // var entityName = GetEntityName(entity); // errors.AppendLine($"({entityName} دچار مشکل شده است)"); // foreach (var error in entry.ValidationErrors) { // errors.AppendLine($"{error.PropertyName}: {error.ErrorMessage}"); // } // } // errors.AppendLine(); // return errors.ToString(); // } private static string GetMessage(DbException ex) { var errors = new StringBuilder(); errors.AppendLine(); #if DEBUG errors.AppendLine($"[{ex.GetType().Name}]"); #endif switch (ex.ErrorCode) { default: errors.AppendLine($"{ex.GetType().Name}({ex.ErrorCode}): {ex.Message}"); break; } errors.AppendLine(); return(errors.ToString()); }
public override bool IsItMyException(DbException exception) { ///"reflection works across" ///System.Data.OracleClient, Oracle.DataAccess.Client (ODP) ///also DDTek.Oracle, Devart.Data.Oracle ///TODO: reference provider directly. return(exception.GetType().Name.Equals("OracleException", StringComparison.OrdinalIgnoreCase)); }
/// <summary> /// <para>データベースが検出した Number を取得します。</para> /// <para>Number が存在しない場合、int.MinValue を返却します。</para> /// </summary> /// <param name="exception">DbException オブジェクト。</param> /// <returns>Number</returns> public static int GetNumber(this DbException exception) { var prop = exception.GetType().GetProperty("Number"); if (prop == null) { return(int.MinValue); } return((int)prop.GetValue(exception, null)); }
public override bool IsSelectForNoWaitLockingException(DbException ex) { if (ex != null && _postgresExceptionNames.Contains(ex.GetType().Name)) { var psqlex = new PostgreSqlExceptionAdapter(ex); return(psqlex.Code == "55P03"); } return(false); }
private static int FindCode(DbException ex) { var t = ex.GetType(); var p = t.GetProperty("Code"); if (p == null) { p = t.GetProperty("Number"); } if (p == null) { return(0); } return((int)p.GetValue(ex, null)); }
/// <summary> /// 根据DbException,获取相应的错误码 /// </summary> /// <param name="ex"></param> /// <returns></returns> public static Int32 GetDbExceptionErrorCode(DbException ex) { try { var dbExceptionBridge = Properties.GetOrAdd(ex.GetType(), type => { var field = type.GetProperty("Number"); return(new PropertyBridge(field)); }); var number = dbExceptionBridge.Read(ex); if (null != number) { return(Convert.ToInt32(number)); } } catch (Exception exception) { ThrowInDebugMode(exception); } return(ex.ErrorCode); }
public static string DBExceptionString(DbException dbx, string sql) { return(LMLoggers.LognLM.FlattenChars(dbx.GetType().Name + "'" + dbx.Message + "' " + dbx.ErrorCode.ToString("x8") + "; " + sql)); }
/// <summary> /// Indicates whether the provided exception has an integer Number property with the supplied value /// </summary> public static bool IsNumber(this DbException exception, int number) => exception != null && ByTypeHelpers.Get(exception.GetType()).IsNumber(exception, number);
/// <summary> /// Constructor to use. Takes MySqlException to display. /// </summary> /// <param name="e">MySqlException to show.</param> /// <param name="status">Table engine statuses to display in advanced information.</param> public SqlErrorDialog(DbException e, string status) { if (e == null) { throw new ArgumentNullException("e"); } if (status == null) { throw new ArgumentNullException("status"); } InitializeComponent(); // Load error icon imageList.Images.Add(SystemIcons.Error); iconLabel.ImageIndex = 0; // Fill text boxes errorText.Text = e.Message; statusText.Text = status; // We try to recognize, if this exception is MySqlException // For this we'll use reflection. We'll try to find property "Number" Type exceptionType = e.GetType(); Debug.Assert(exceptionType != null, "Failed to retrieve type information for exception!"); // Extract property information PropertyInfo numberProperty = exceptionType.GetProperty("Number"); // If there is Number property, extract its value object numberValueObject = null; if (numberProperty != null) { try { // Try to get value of Number property numberValueObject = numberProperty.GetValue(e, null); } catch (Exception ex) { // This is bad, but not fatal - we can show unknown error code Debug.Fail("Failed to get value for Number property!", ex.ToString()); } } else { // This is bad, but not fatal - we can show unknown error code Debug.Fail("Failed to extract Number property description!"); } // If extracted value is not null, convert it to string and append to error label if (numberValueObject != null) { errorLabel.Text = String.Format(CultureInfo.CurrentCulture, errorLabel.Text, numberValueObject.ToString()); } // If value is null, append unknow error code else { errorLabel.Text = String.Format(CultureInfo.CurrentCulture, errorLabel.Text, Resources.UnknownErrorCode); } }
public override bool IsItMyException(DbException exception) { return(exception.GetType().Name.Equals("MySqlException", StringComparison.OrdinalIgnoreCase)); }
public override bool IsItMyException(DbException exception) { return(exception.GetType() == typeof(SqlException)); }
public static string DBExceptionString(DbException dbx, string sql) { return LMLoggers.LognLM.FlattenChars(dbx.GetType().Name + "'" + dbx.Message + "' " + dbx.ErrorCode.ToString("x8") + "; " + sql); }