Search code examples
.netasp.netexceptiontype-conversionpage-lifecycle

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 without using string comparison...

Thanks in advance.


Solution

  • Can you try somethink like this:

    var ex = Context.Server.GetLastError();
    
    var soapEx = ex as SoapException;
    if(soapEx != null)
    {
        //Handle SoapException
    }