Back in RC1, I would do this:
[HttpPost]
public IActionResult Post([FromBody]string something)
{
try{
// ...
}
catch(Exception e)
How about creating a custom ObjectResult class that represents an Internal Server Error like the one for OkObjectResult
?
You can put a simple method in your own base class so that you can easily generate the InternalServerError and return it just like you do Ok()
or BadRequest()
.
[Route("api/[controller]")]
[ApiController]
public class MyController : MyControllerBase
{
[HttpGet]
[Route("{key}")]
public IActionResult Get(int key)
{
try
{
//do something that fails
}
catch (Exception e)
{
LogException(e);
return InternalServerError();
}
}
}
public class MyControllerBase : ControllerBase
{
public InternalServerErrorObjectResult InternalServerError()
{
return new InternalServerErrorObjectResult();
}
public InternalServerErrorObjectResult InternalServerError(object value)
{
return new InternalServerErrorObjectResult(value);
}
}
public class InternalServerErrorObjectResult : ObjectResult
{
public InternalServerErrorObjectResult(object value) : base(value)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
public InternalServerErrorObjectResult() : this(null)
{
StatusCode = StatusCodes.Status500InternalServerError;
}
}
return StatusCode((int)HttpStatusCode.InternalServerError, e);
Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).
HttpStatusCode
is an enumeration in System.Net
.