一个更好的办法来处理这个截至目前(1.1)是为此在Startup.cs
的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的博客。