Skip to content

Instantly share code, notes, and snippets.

@benjanderson
Created March 23, 2015 16:15

Revisions

  1. benjanderson created this gist Mar 23, 2015.
    39 changes: 39 additions & 0 deletions SqlExceptionCreator
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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);
    }
    }
    }