DotNet Core 2.1自定义例外

时间:2018-11-02 19:26:40

标签: c# asp.net-core

我创建了一个自定义异常,我想再添加几个,但是我无法使其正常工作。

这是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;
}

我似乎很简单,但是我不确定。任何帮助将不胜感激。

当我调试Exception时,它始终为null,并且永远无法继续根据Exception类型(GoogleAuthenticationException)进行操作

1 个答案:

答案 0 :(得分:0)

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

更新代码:

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