Skip to content

Instantly share code, notes, and snippets.

@NickCraver
Last active April 16, 2019 01:56
Show Gist options
  • Save NickCraver/e2dcd69f5e9ed99175fe2a8eb05cfcb3 to your computer and use it in GitHub Desktop.
Save NickCraver/e2dcd69f5e9ed99175fe2a8eb05cfcb3 to your computer and use it in GitHub Desktop.
SQL Exception handy helpers
// Here are some example usages for unimportant jobs we have where crap happens occasionally:
/// <summary>
/// intended for database commands that might deadlock, but are just "nice to haves"; we don't care if they deadlock every now and then
/// and we DON'T want them to block execution of the rest of /daily or /hourly! this returns -1 if deadlocked, otherwise, returns
/// the # of rows that the SQL command affected
/// </summary>
private int ExecuteIgnoreDeadlocks(string sql, object param = null, bool logDeadlock = false)
{
try
{
return DB.Execute(sql, param);
}
catch (SqlException sex) when (sex.Is(SqlErrorCode.TransactionDeadlocked_1205))
{
// don't care, this will be run every hour, so SOME of them will succeed
// ...but we may care!
if(logDeadlock) Current.LogException(sex);
return -1;
}
}
/// <summary>
/// The equivalent of ExecuteIgnoreDeadlocks, except it returns rows.
///
/// In the event of a deadlock, it returns null.
/// </summary>
private List<dynamic> QueryIgnoreDeadlocks(string sql)
{
try
{
return DB.Query(sql);
}
catch (SqlException sex) when (sex.Is(SqlErrorCode.TransactionDeadlocked_1205))
{
// don't care, this will be run every hour, so SOME of them will succeed
return null;
}
}
using System;
using System.Data.SqlClient;
namespace StackOverflow
{
static partial class ExtensionMethods
{
public static bool IsSqlError(this Exception ex, SqlErrorCode errorCode)
{
var sqlEx = ex as SqlException;
return Is(sqlEx, errorCode);
}
public static bool Is(this SqlException ex, SqlErrorCode errorCode)
{
return ex != null && ex.Number == (int)errorCode;
}
}
public enum SqlErrorCode
{
/// <summary>
/// Usually FK constraint violations
/// </summary>
/// <remarks>
/// Here are all native sql server errors that are a part of the SQLSTATE (ODBC) 23000 constraint error code:
///
/// select *
/// from sysmessages
/// where error in ( 233, 272, 273, 515, 530, 547, 1505, 1508, 2601, 2615, 2626, 2627, 3604, 3605 )
/// and msglangid = 1033
/// </remarks>
// ReSharper disable InconsistentNaming
ConstraintViolation_547 = 547,
DatabaseReadOnly_3906 = 3906,
InsertNullIntoNotNull_515 = 515,
TransactionDeadlocked_1205 = 1205,
UniqueConstraintViolaton_2627 = 2627,
UniqueIndexViolation_2601 = 2601,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment