Back in RC1, I would do this:
[HttpPost]
public IActionResult Post([FromBody]string something)
{
try{
// ...
}
catch(Exception e)
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<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
}
Above snippet taken from Scott Sauber's blog.
From what I can see there are helper methods inside the ControllerBase
class. Just use the StatusCode
method:
[HttpPost]
public IActionResult Post([FromBody] string something)
{
//...
try
{
DoSomething();
}
catch(Exception e)
{
LogException(e);
return StatusCode(500);
}
}
You may also use the StatusCode(int statusCode, object value)
overload which also negotiates the content.
When you want to return a JSON response in MVC .Net Core You can also use:
Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });
This will return both JSON result and HTTPStatus. I use it for returning results to jQuery.ajax().
You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode
and Microsoft.AspNetCore.Http.StatusCodes
to form your response, if you don't wish to hardcode specific numbers.
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. My code now looks like this;
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
If you need a body in your response, you can call
return StatusCode(StatusCodes.Status500InternalServerError, responseObject);
This will return a 500 with the response object...
For aspnetcore-3.1, you can also use Problem()
like 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);
}