0

<%@ 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;
        }
    }
}

大家好,

我正在开发一个应用程序,我想在该应用程序中检查 Exception 对象的 InnerException 属性是否为 null。如果是,则显示 Exception 对象的 Message 属性。否则,显示由 InnerException 属性返回的 Exception 对象的 Message 属性。这是我到目前为止所拥有的。为了做到这一点,我创建了一个 Page_Load 事件处理程序,但我被困在了 else 部分。有人能帮我吗?我还包括了错误页面,以防有人想知道这个异常错误消息将在哪里显示。

4

2 回答 2

0

.NET actually has a method that would solve your problem, without you having to do the testing yourself.

You can just do:

var rootCause = ex.GetBaseException();
lblError.Text = rootCause.Message;

GetBaseException() will actually walk down the InnerException chain for you recursively, until it gets to the last exception where InnerException is null.

于 2017-11-30T04:43:20.290 回答
0

如果您只需要一条 InnerException 消息,您可以将其访问为

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

或更短

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

但异常 inInnerException也可能包含一个InnderException. 如果要访问最深的,可以使用以下递归方法:

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

lblError.Text = UnwrapExceptionMessage(ex);
于 2017-11-30T04:46:29.513 回答