提问人: 提问时间:10/15/2019 更新时间:10/15/2019 访问量:468
我怎样才能得到null的对象(如图所示)
How can i get the object that was null as (shown in the picture)
问:
带注释的异常描述我正在为 ASP.NET Core 项目创建一个中间件异常处理程序,并且我正在尝试获取异常的来源(如在导致异常的对象中)。当我使用调试器时,我可以看到该对象,但我无法以编程方式获取它。
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ErrorHandlingMiddleware> _logger;
public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception ex)
{
_logger.LogError(ex, ex.Message);
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
var result = JsonConvert.SerializeObject(new { Error = ex.Message, Soure = ex.Source });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
我希望异常中的源属性包含它,但它只是显示类。
答:
1赞
Christopher
10/15/2019
#1
据我所知,只有一种方法可以做你想做的事: 写一个尝试...catch 块。这根本不可行。
实际上,查找甚至不是这个异常的悲哀。它来自函数解析机制中的某个地方。老实说,我不确定代码是否准确地抛出它,但我知道变量查找完成了它的工作(正确获取、存储和返回“null”),并且对此没有任何过错。
null 值与 Bonehead Exceptions 一起出现。正如字面上提到的。去防止它发生:“骨头异常是你自己的错,你本可以阻止它们,因此它们是你代码中的错误。你不应该抓住他们;这样做是在代码中隐藏一个错误。相反,您应该编写代码,以便从一开始就不可能发生异常,因此不需要捕获异常。这个参数是空的,类型转换是坏的,索引是超出范围的,你试图除以零——这些都是你本来可以很容易地预防的问题,所以首先要防止混乱,而不是试图清理它。
老实说,我无法真正理解这个功能。您是否正在尝试将管理员用户放入数据库?如果是这样,“AdminResponse”在这种情况下意味着什么?
评论
0赞
10/15/2019
我的目标是创建一个可以吐出属性的处理程序,如图所示,我故意导致异常来测试它,它能够返回发生异常的类,我想走得更远一点,并从处理程序中吐出导致错误的属性,如图中箭头所示
0赞
10/15/2019
在图片中,异常有明确的行,说属性“查找”是 null,我想创建一个处理程序,找出(在任何情况下)我尝试访问并发现 null 的属性
0赞
Mr.Mindor
10/15/2019
@Hackavist in general, I don't think this is going to be possible in production code without, as Christopher is pointing out, a lot of work. You are able to get that while debugging because of all the extra work and meta data the debugger is using. That information isn't tracked outside the debugger.
0赞
Christopher
10/15/2019
@Hackavist: The thing is - the Property or Field is in no way, shape or form at fault for this. It did it's job. It took a value. It stored it. It handed it back. Unlike Darth Vader when defending the 1st Death Star, it did it's job. The function whose name you have now hidden is who is responsible for this mess.
0赞
10/15/2019
I get your point now @Christopher, i will try fix all the manageable errors as you mentioned earlier and to follow the exception handling guide lines, Thank you for your Time and Effort
评论
lookup
lookup