-1

そのため、カスタム例外クラス ( と呼びましょうCustomException) を作成し、クラスにないいくつかのカスタム プロパティを作成しましたException。global.asax.cs ファイルにはApplication_Error、例外が発生するたびに呼び出されるメソッドがあります。メソッドServer.GetLastError()をトリガーした例外を取得するために使用しています。Application_Error問題は、カスタム プロパティと共にスローされるオブジェクトではなく、オブジェクトServer.GetLastError()のみを取得することです。基本的に、はによって取得されるときにオブジェクトに分解されるため、に関連付けられているカスタム プロパティは失われます。ExceptionCustomExceptionCustomExceptionExceptionServer.GetLastError()CustomException

削除されたバージョンではなく、GetLastError()実際にオブジェクトを取得する方法はありますか? これは、通常.CustomExceptionExceptionException

Application_Error:

protected void Application_Error(object sender, EventArgs e)
{
    // This var is Exception, would like it to be CustomException
    var ex = Server.GetLastError();           

    // Logging unhandled exceptions into the database
    SystemErrorController.Insert(ex);

    string message = ex.ToFormattedString(Request.Url.PathAndQuery);

    TraceUtil.WriteError(message);
}

CustomException:

public abstract class CustomException : System.Exception
{        
    #region Lifecycle

    public CustomException ()
        : base("This is a custom Exception.")
    {
    }

    public CustomException (string message)
        : base(message)
    {
    }

    public CustomException (string message, Exception ex)
        : base(message, ex)
    {
    }

    #endregion

    #region Properties

    // Would like to use these properties in the Insert method
    public string ExceptionCode { get; set; }
    public string SourceType { get; set; }
    public string SourceDetail { get; set; }
    public string SystemErrorId { get; set; }

    #endregion        
}
4

1 に答える 1

0

Server.GetLastError の結果を CustomException にキャストするだけです。

var ex = Server.GetLastError() as CustomException;

場合によっては、CustomException が StackTrace の最上位の例外にならないことがあります。この場合、正しいものを見つけるために InnerExceptions をナビゲートする必要があります。

カスタム例外の設計方法については、@scott-chamberlain のリンクを確認してください。

于 2014-07-31T22:59:26.157 に答える