c# - 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)做事
解决方案
好的,我知道这很简单...... GoogleAuthenticationException 实际上是 System.Exception 的内部异常。感谢 jmdon 和 Kirk Larkin 的快速响应和指导。
更新代码:
var exceptionHandler = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandler?.Error?.InnerException as GoogleAuthenticationException;
推荐阅读
- python - 为什么 if 和 elif 语句都在我的 python 代码中执行?
- jira - 是否可以开发具有 RESTful 功能的 Jira 插件以编程方式创建问题?
- angular - Angular - 编译链接文件
- rabbitmq - 鼠兔`从空队列中弹出`
- javascript - 如何在 javascript 中将 JSON 修改为特定的 SQL 查询格式?
- android - 通过什么因素增加不同屏幕图标的宽度/高度 - Android
- python - 我在烧瓶中遇到端口问题,如何更改端口?
- r - 将格式应用于 R 中的多个数组
- python-3.x - ArgumentError: hasproperty of NULL PyObject using PyPlot in julia 1.5.3 in JupyterNotebook
- r - 模型适合 Lavaan CFA。这段代码有什么问题?