一種更好的方式來處理這種截至目前(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);
}
}
更多信息here。
在你想獲得實際的異常數據的情況下,你可能會在return
語句之前添加此上述Get()
。
// 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's blog。
錯誤的請求是HTTP代碼400和客戶端發送無效請求/數據(即失敗的模型驗證)的信號。 http代碼500是針對內部服務器錯誤,不完全一樣;) – Tseng
啊,謝謝!我不確定BadRequest是什麼,這是有道理的 –