Skip to content

Instantly share code, notes, and snippets.

@mrwizard82d1
Forked from benjanderson/SqlExceptionCreator
Created July 3, 2016 06:42
Show Gist options
  • Select an option

  • Save mrwizard82d1/1503eee6302c947e7880004b4a6c3269 to your computer and use it in GitHub Desktop.

Select an option

Save mrwizard82d1/1503eee6302c947e7880004b4a6c3269 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