Skip to content

Instantly share code, notes, and snippets.

@benjanderson
Created March 23, 2015 16:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save benjanderson/07e13d9a2068b32c2911 to your computer and use it in GitHub Desktop.
Save benjanderson/07e13d9a2068b32c2911 to your computer and use it in GitHub Desktop.
Creates SqlException through reflection and sets ErrorMessage and ErrorCode. Be aware this reflects private functionality which is likely to change, do not use this in production code
public static class SqlExceptionCreator
{
public static SqlException Create(string message, int errorCode)
{
SqlException exception = Instantiate<SqlException>();
SetProperty(exception, "_message", message);
var errors = new ArrayList();
var errorCollection = Instantiate<SqlErrorCollection>();
SetProperty(errorCollection, "errors", errors);
var error = Instantiate<SqlError>();
SetProperty(error, "number", errorCode);
errors.Add(error);
SetProperty(exception, "_errors", errorCollection);
return exception;
}
private static T Instantiate<T>() where T : class
{
return FormatterServices.GetUninitializedObject(typeof(T)) as T;
}
private static void SetProperty<T>(T targetObject, string fieldName, object value)
{
var field = typeof(T).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
field.SetValue(targetObject, value);
}
else
{
throw new InvalidOperationException("No field with name " + fieldName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment