How to get exception type without string name (ex.GetType().FullName) comparison in ASP.NET Page_Error handler?
Is there a better way to do this than to check for Exception string?
I would rather have this catch-all error handled on the page, but for SOAP exceptions (web-service calls) I need to log the details of the actual exception that occured on the server, not the client.
The ".Detail.InnerText" property isn't in a generic exception, and can only be gotten after casting a generic exception to a SOAP exception.
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = Context.Server.GetLastError();
if (ex.GetType().FullName == "System.Web.Services.Protocols.SoapException")
{
System.Web.Services.Protocols.SoapException realException = (System.Web.Services.Protocols.SoapException)ex;
Response.Clear();
Response.Output.Write(@"<div style='color:maroon; border:solid 1px maroon;'><pre>{0}</pre></div>", realException.Detail.InnerText);
Response.Output.Write("<div style='color:maroon; border:solid 1px maroon;'><pre>{0}\n{1}</pre></div>", ex.Message, ex.StackTrace);
Context.ClearError();
Response.End();
}
}
I would think there is a way to get at the underlying Exception's type wi开发者_StackOverflow中文版thout using string comparison...
Thanks in advance.
Can you try somethink like this:
var ex = Context.Server.GetLastError();
var soapEx = ex as SoapException;
if(soapEx != null)
{
//Handle SoapException
}
Either use the as
operator:
var ex = Context.Server.GetLastError();
var soapEx = ex as SoapException;
if(soapEx != null)
{
//Handle SoapException
}
(See Dima's answer.)
Or compare type objects:
var ex = Context.Server.GetLastError();
if (ex.GetType() == typeof(SoapException) {
..
}
One assumes you will want to access some member of SoapException
, the as
approach avoids multiple type checks.
if (ex is System.Web.Services.Protocols.SoapException)
{
var soapEx = (System.Web.Services.Protocols.SoapException)ex;
// do your thing
}
精彩评论