Coder Perfect

How can I get an HTTP 500 response from the ASP.NET Core RC2 Web Api?

Problem

I used to do this in RC1:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}

HttpStatusCodeResult is no longer available in RC2, and I can’t locate anything that allows me to return a 500 type of IActionResult.

Is the strategy for what I’m asking now completely different? In Controller programming, do we no longer use try-catch? Do we just let the framework return to the API caller a general 500 error? How can I see the exact exception stack during development?

Asked by Mickael Caruso

Solution #1

There appear to be assistance methods within the ControllerBase class. Use the StatusCode method instead:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

The StatusCode(int statusCode, object value) overload can also be used to negotiate the content.

Answered by Federico Dipuma

Solution #2

If you don’t want to hardcode certain values, you can use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode and Microsoft.AspNetCore.Http.StatusCodes.

return  StatusCode(StatusCodes.Status500InternalServerError);

UPDATE: Aug 2019

Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions I found that I had to construct a new StatusCodeResult object found in the Microsoft.AspNetCore.Mvc.Core assembly. This is how my code now looks:

return new StatusCodeResult(StatusCodes.Status500InternalServerError);

Answered by Edward Comeau

Solution #3

You can contact if you require a body in your response.

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

With the response object, you’ll get a 500…

Answered by David McEleney

Solution #4

You can also use Problem() in aspnetcore-3.1, as shown below.

https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1
 [Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
    [FromServices] IWebHostEnvironment webHostEnvironment)
{
    if (webHostEnvironment.EnvironmentName != "Development")
    {
        throw new InvalidOperationException(
            "This shouldn't be invoked in non-development environments.");
    }

    var context = HttpContext.Features.Get<IExceptionHandlerFeature>();

    return Problem(
        detail: context.Error.StackTrace,
        title: context.Error.Message);
}

Answered by Teoman shipahi

Solution #5

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 /Error route. You won’t have to include try-catch blocks to every action you write as a result of this.

Of course, you’ll need to include an ErrorController that looks something like this:

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

More information here.

If you wish to access the actual exception data, put this before the return statement in the Get() method.

// 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
}

The above is a sample from Scott Sauber’s blog.

Answered by galdin

Post is based on https://stackoverflow.com/questions/37793418/how-to-return-http-500-from-asp-net-core-rc2-web-api