截至目前(1.1版本),更好的处理方法是在Startup.cs
文件中的Configure()
方法中执行此操作:
A better way to handle this as of now (1.1) is to do this in Startup.cs
's Configure()
:
app.UseExceptionHandler("/Error");
这将执行/Error
路由。 这样可以避免在您编写的每个操作中添加try-catch块。
当然,您需要添加类似于以下内容的ErrorController:
[Route("[controller]")]
public class ErrorController : Controller
{
[Route("")]
[AllowAnonymous]
public IActionResult Get()
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
更多信息请点击此处。
如果您想获取实际的异常数据,在上述Get()
方法中,在return
语句之前添加以下内容即可。
// Get the details of the exception that occurred
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionFeature != null)
{
// Get which route the exception occurred at
string routeWhereExceptionOccurred = exceptionFeature.Path;
// Get the exception that occurred
Exception exceptionThatOccurred = exceptionFeature.Error;
// TODO: Do something with the exception
// Log it with Serilog?
// Send an e-mail, text, fax, or carrier pidgeon? Maybe all of the above?
// Whatever you do, be careful to catch any exceptions, otherwise you'll end up with a blank page and throwing a 500
}
以上代码片段摘自Scott Sauber的博客。