Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Exception Extensions - C#

RSS
Modified on Thu, Jun 18, 2020, 12:20 PM by Administrator Categorized as ┬ĚNet Framework

Code

using System;
using System.Collections.Generic;
using System.Linq;
public static class ExceptionExtensions
{
    private static List<string> _ignoreErrors;
    static ExceptionExtensions()
    {
        _ignoreErrors = new List<string>() 
        {
            "See the inner exception for details",
            "An error occurred while updating the entries. See the inner exception for details."
        };
    }
    public static string Recurse(this Exception ex)
    {
        var result = new List<string>();

        var e2 = ex;

        while (e2 != null)
        {
            if (!_ignoreErrors.Contains(e2.Message))
            {
                result.Add(e2.Message);
            }

            e2 = e2.InnerException;
        }

        return string.Join(" ", result);
    }

    public static string RecurseForDb(this Exception ex)
    {
        var result = new List<string>();

        var e2 = ex;

        while (e2 != null)
        {
            if (e2 is System.Data.Entity.Validation.DbEntityValidationException)
            {
                var e3 = e2 as System.Data.Entity.Validation.DbEntityValidationException;

                var msgs = e3.EntityValidationErrors
                    .SelectMany(a => a.ValidationErrors)
                    .Select(a => a.ErrorMessage);

                result.AddRange(msgs);

            }
            else if (!_ignoreErrors.Contains(e2.Message))
            {
                result.Add(e2.Message);
            }

            e2 = e2.InnerException;
        }

        return string.Join(" ", result);
    }

}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2020, Patrick Jasinski.