Je suis actuellement en train de développer une application BackOffice avec ASP.NET MVC permettant de gérer un moteur d’application.
Une des section de ce site permet de visualiser les Logs des Exceptions levées par les applications qui sont stockée en base de donnée.
J’ai été confronté à un problème d’affichage du détail des Exceptions. J’ai donc crée un Exception HTML Formatter afin d’afficher le détail des Exceptions de manière clair et formaté avec du style CSS.
Voici le code :
public class ExceptionFormatter
{
#region Private Fields
private readonly Exception _ex;
#endregion
#region Public Properties
public string Title { get; set; }
public string CssClass { get; set; }
#endregion
#region Constructors
public ExceptionFormatter(Exception ex)
{
if (ex == null) throw new ArgumentNullException();
_ex = ex;
}
#endregion
#region Public Methods
public string Format()
{
var sb = new StringBuilder();
sb.AppendFormat("<div class=\"" + CssClass + "\">");
;
BuildErrorMessage(sb, _ex);
sb.Append("</div>");
sb.Replace(Environment.NewLine, "<br/>");
return sb.ToString();
}
#endregion
#region Private Static Methods
private void BuildErrorMessage(StringBuilder sb, Exception ex)
{
sb.AppendFormat("<h1 class=\"" + CssClass + "\">{0}</h1>", Title);
sb.Append("<hr width=100% size=1 color=silver>");
if (!String.IsNullOrEmpty(ex.Message))
{
sb.AppendFormat("<h2 class=\"" + CssClass + "\"><i>Une exception de type '{0}' a été levée</i></h2>", ex.GetType().FullName);
sb.Append("<font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif\">");
sb.AppendFormat("<strong>Description :</strong> {0}<br/>", ex.Message);
sb.AppendFormat("<strong>Détails de l'exception :</strong> Une exception de type '{0}' a été levée<br/>", ex.GetType().Name);
}
if (!String.IsNullOrEmpty(ex.Source))
{
sb.Append("<strong>Erreur source :</strong>");
sb.AppendFormat("<code><pre class=\"" + CssClass + "\">{0}</code></pre><br/>", ex.Source);
}
if (!String.IsNullOrEmpty(ex.Source))
{
sb.Append("<strong>Trace de la pile :</strong>");
sb.AppendFormat("<code><pre class=\"" + CssClass + "\">{0}</code></pre><br/>", ex.StackTrace);
}
if (ex.InnerException != null)
{
BuildErrorMessage(sb, ex.InnerException);
}
}
#endregion
}
Exemple d’utilisation :
try
{
int a = 0;
int b = 2;
int c = b / a;
}
catch (Exception ex)
{
string s = new ExceptionFormatter(ex)
{
Title = "Une Erreur est survenue !",
CssClass = "exception"
}.Format();
}
Style CSS :
div.exception
{
overflow: auto;
overflow-x: auto;
overflow-y: auto;
width: 1000px;
}
.exception h1
{
font-family: "Verdana";
font-weight: normal;
font-size: 18pt;
color: red;
}
.exception h2
{
font-family: "Verdana";
font-weight: normal;
font-size: 14pt;
color: maroon;
margin-bottom: 5px;
}
.exception pre
{
font-family: "Lucida Console";
font-size: .9em;
background-color: rgb(255, 255, 204);
padding-top: 10px;
padding-bottom: 10px;
}
Exemple de sortie :
A Bientôt :)
6ba86fa9-4270-4ffc-93e8-9bfff37d822a|0|.0
C#
c#, exception