How to return HTTP 500 from ASP.NET Core RC2 Web Api?

前端 未结 8 2451
忘掉有多难
忘掉有多难 2020-12-04 17:01

Back in RC1, I would do this:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
            


        
8条回答
  •  囚心锁ツ
    2020-12-04 17:41

    A better way to handle this as of now (1.1) is to do this in Startup.cs's Configure():

    app.UseExceptionHandler("/Error");
    

    This will execute the route for /Error. This will save you from adding try-catch blocks to every action you write.

    Of course, you'll need to add an ErrorController similar to this:

    [Route("[controller]")]
    public class ErrorController : Controller
    {
        [Route("")]
        [AllowAnonymous]
        public IActionResult Get()
        {
            return StatusCode(StatusCodes.Status500InternalServerError);
        }
    }
    

    More information here.


    In case you want to get the actual exception data, you may add this to the above Get() right before the return statement.

    // Get the details of the exception that occurred
    var exceptionFeature = HttpContext.Features.Get();
    
    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
    }
    

    Above snippet taken from Scott Sauber's blog.

提交回复
热议问题