I'm up at work trying to understand some of what is going on in our code base. I have so much to learn. It appears that one may put a method in the Global.asax.cs file which catches any error and then tries to react. I've done some Googling and have found this thread which suggest that one may capture the error and then write an error message to the screen like so:
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
string errorHtml = "The error:<br />" + ex.Message.ToString();
Response.Write(errorHtml.ToString());
Server.ClearError();
}
OK. I've found another thread here which seems to conditional check to see if the exception is an HttpException. If the exception is an HttpException, the method "redirects" instead of using Response.Write
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex.GetType() == typeof(HttpException))
{
if (ex.Message.Contains("NoCatch") || ex.Message.Contains("maxUrlLength")) return;
Server.Transfer("MyErrorPage.aspx");
}
string errorHtml = "The error:<br />" + ex.Message.ToString();
Response.Write(errorHtml.ToString());
Server.ClearError();
}
One of my teammates, a Mr. Byron Lousiq-Nont, has something comparable going on in our app shaped like so:
protected void Application_Error()
{
var ex = Server.GetLastError().GetBaseException();
if (ex.GetType().IsDerivedFrom
{
.IsDerivedFrom is an extension of Type which fascinates me. (This is the real reason for this blog posting.) Byron's code:
using System;
public static class TypeExtensions
{
public static bool IsDerivedFrom
{
Type baseType = typeof(T);
if (baseType.FullName == type.FullName) return true;
if (type.IsClass)
{
return baseType.IsClass
? type.IsSubclassOf(baseType)
: baseType.IsInterface
? IsImplemented(type, baseType)
: false;
}
else if (type.IsInterface && baseType.IsInterface)
return IsImplemented(type, baseType);
return false;
}
public static bool IsImplemented(Type type, Type baseType)
{
Type[] faces = type.GetInterfaces();
foreach (Type face in faces)
{
if (baseType.Name.Equals(face.Name)) return true;
}
return false;
}
}
I found myself "decoding" the bit in the center. I suppose it reads like so:
Boolean returnBoolean;
if (baseType.IsClass)
{
returnBoolean = type.IsSubclassOf(baseType);
} else {
if (baseType.IsInterface)
{
returnBoolean = IsImplemented(type, baseType);
} else {
returnBoolean = false;
}
}
return returnBoolean;
Cool stuff! I didn't know .GetType() existed or that type could be extended. .GetType() appears to be of the Spring.Web.Mvc namespace. I found this further thread which suggests one enables an extension method by including the namespace in the using statements, but that doesn't seem to be applicable to Byron's implementation. I wonder if Spring.NET is empowering something I cannot yet see.
No comments:
Post a Comment