首页 > 解决方案 > DotNet Core 2.1 自定义异常

问题描述

我创建了一个自定义异常,我想再添加一些,但我无法让它正常工作。

这是 1 个例外

[Serializable]
public class GoogleAuthenticationException : Exception
{
    public GoogleAuthenticationException() { }
    public GoogleAuthenticationException(string message)
        : base(message) { }
    public GoogleAuthenticationException(string message, Exception inner)
        : base(message, inner) { }
}

在我的启动中,我使用

app.UseExceptionHandler("/Identity/Error");

然后在我的 Error.cshtml.cs 中。我想识别自定义异常,然后根据异常类型(GoogleAuthenticationException)做一些事情

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public void OnGet()
{
    var exceptionHandler = HttpContext.Features.Get<IExceptionHandlerFeature>();
    var exception = exceptionHandler?.Error as GoogleAuthenticationException;

    if (exception is GoogleAuthenticationException)
        //Do Some Stuff -- But I can never make it here
    else if (exception is AnotherCustomException)
        //Do Some OtherStuff 

    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}

我想念的东西似乎很简单,但我不确定。任何帮助将不胜感激。

当我调试时,异常始终为空,我永远无法继续基于异常类型(GoogleAuthenticationException)做事

标签: c#asp.net-core

解决方案


好的,我知道这很简单...... GoogleAuthenticationException 实际上是 System.Exception 的内部异常。感谢 jmdon 和 Kirk Larkin 的快速响应和指导。

更新代码:

var exceptionHandler = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandler?.Error?.InnerException as GoogleAuthenticationException;

推荐阅读