วิธีที่ดีกว่าในการจัดการนี้ ณ ขณะนี้ (1.1) คือการทำเช่นนี้ใน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
}
ด้านบนข้อมูลโค้ดนำมาจากบล็อกของสกอตต์ของ Sauber