Click here to Skip to main content
15,125,351 members
Articles / General Programming / Exceptions
Tip/Trick
Posted 31 Jan 2012

Stats

24.5K views
7 bookmarked

Render Exceptions in an Entity Framework application

Rate me:
Please Sign up or sign in to vote.
4.85/5 (5 votes)
8 Feb 2012CPOL
Extension Method for exceptions that give a useful text even on Entity Framework Exceptions

Did you know that exceptions thrown by Entity Framework contain useful information? They are buried in some properties of an inner exception. Here's the code that makes them visible:


C#
public static class Extensions
{
    /// <summary>
    /// Renders an exception with messages and stack traces
    /// </summary>
    /// <param name="ex">The exception to render</param>    
    /// <param name="noTrace">Whether trace information should be omitted</param>
    /// <returns>A string containing messages and stack traces</returns>
    public static string Render(this Exception ex, bool noTrace = false)
    {
        var s = new StringBuilder("\n");
        int i = 0;
        do
        {
            s.AppendFormat("{0:#\\. inner E;;E}xception ({1}):\n   {2}\n", 
                i++, 
                ex.GetType().Name, 
                ex.Message.Replace("\n", "\n   "));
            if (ex is UpdateException)
            {
                foreach (var stateEntry in ((UpdateException)ex).StateEntries)
                {
                    var entity = stateEntry.Entity ?? new object();
                    s.AppendFormat("     {0} {1}: {2}\n", stateEntry.State, entity.GetType().Name, entity);
                    var values =
                        stateEntry.State == EntityState.Deleted
                            ? stateEntry.OriginalValues
                            : stateEntry.CurrentValues;
                    for (int j = 0; j < values.FieldCount; j++)
                    {
                        var currentValue = values[j];
                        var originalValue =
                            stateEntry.State == EntityState.Added
                                ? currentValue
                                : stateEntry.OriginalValues[j];
                        s.AppendFormat(originalValue.Equals(currentValue) ? "      {0}: <{1}>\n" : "      {0}: <{1}>→<{2}\n",
                                       values.GetName(j), originalValue, currentValue);
                    }
                }
            }
            s.AppendFormat(noTrace ? "\n" : "Trace:\n{0}\n", ex.StackTrace);
            ex = ex.InnerException;
        }
        while (ex != null);
        return s.ToString();
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

Comments and Discussions

 
GeneralThanks for this snippet. How to properly use them? Please wr... Pin
evlntnt16-Feb-12 3:16
Memberevlntnt16-Feb-12 3:16 
GeneralThe Idea is correct and it is a usefull. But as mentioned by... Pin
chrisgl848-Feb-12 10:34
Memberchrisgl848-Feb-12 10:34 
GeneralI've made a little update that fixed the code for deletes an... Pin
Harry von Borstel8-Feb-12 4:22
MemberHarry von Borstel8-Feb-12 4:22 
GeneralReason for my vote of 3 Very nifty tip. nicely done. but is ... Pin
Dean Oliver31-Jan-12 19:30
MemberDean Oliver31-Jan-12 19:30 
Reason for my vote of 3
Very nifty tip. nicely done. but is this the cleanest way to go about doing this?
GeneralRe: Thanks! Does anyone have an idea how to make it "cleaner"? Pin
Harry von Borstel31-Jan-12 21:45
MemberHarry von Borstel31-Jan-12 21:45 
GeneralRe: Thanks! Does anyone have an idea how to make it "cleaner"? Pin
Sandesh Deshmukh10-May-12 10:16
MemberSandesh Deshmukh10-May-12 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.