Created
March 23, 2015 16:15
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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