Search code examples
asp.netexceptioninner-exception

How can I check if the InnerException property of the Exception object is null?


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Error.aspx.cs" Inherits="XEx21HandleErrors.Error" %>

<asp:Content ContentPlaceHolderID="mainPlaceholder" runat="server">
    <h1 class="text-danger">An error has occurred</h1>
    <div class="alert alert-danger">
        <p><asp:Label ID="lblError" runat="server"></asp:Label></p>
    </div>
    <asp:Button ID="btnReturn" runat="server" Text="Return to Order Page" 
        PostBackUrl="~/Order.aspx" CssClass="btn btn-danger" />
</asp:Content>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace XEx21HandleErrors
{
    public partial class Error : System.Web.UI.Page
    {
        private Exception ex;
        protected void Page_Load()
        {

            if (ex.InnerException == null)
            {
                lblError.Text = ex.Message;
            }
            else ex.InnerException;
        }
    }
}

Hello All,

I am working on an application in which I want to check if the InnerException  property of the Exception object is null.If it is, display the Message property of the Exception object. Otherwise, display the Message property of the Exception object that’s returned by the InnerException property. Here is what I have so far. In order to do I am asking, I have created a Page_Load event handler, but I am stuck at the else part. Can someone help me? I also included the error page in case anyone wants to know exactly where this exception error message will be shown at.


Solution

  • If you need just a message of InnerException you could access it as

    if (ex.InnerException == null)
    {
        lblError.Text = ex.Message;
    }
    else
    {
        lblError.Text = ex.InnerException.Message;
    }
    

    or shorter

    lblError.Text = ex.InnerException?.Message ?? ex.Message;
    

    But exception in InnerException could also contain an InnderException. If you want to access the deepest one you could use following recursive method:

    static string UnwrapExceptionMessage(Exception ex)
    {
        return ex.InnerException != null ? UnwrapExceptionMessage(ex.InnerException) : ex.Message;
    }
    
    lblError.Text = UnwrapExceptionMessage(ex);