The Microsoft.AspNetCore.Mvc.Controller
base class doesn't have an equivalent of BadRequest()
, Ok()
, NoContent()
, etc. for returning HTTP 500 status codes.
Why can't we do?
try{
oops();
}
catch(Excpetion e){
//some handling
return InternalServerError(e);
}
I know can do return StatusCode(500);
, but we are trying to be more consistent with our HTTP codes and would like to know if there is something more consistent with Ok()
for returning a 500 code?
To configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware: Catches and logs unhandled exceptions. Re-executes the request in an alternate pipeline using the path indicated.
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.
ASP.NET Core 2.x doesn't have InternalServerError method. Instead you can include the following library.
using Microsoft.AspNetCore.Http;
And then use the following code.
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
Or if you want to add the exception along with the response, try the following code
var result = StatusCode(StatusCodes.Status500InternalServerError, exception);
return result;
If just like me you didn't understand where the StatusCode method is coming from in Karim's answer, this code will work just as well:
var errorObjectResult = new ObjectResult(exceptionMessage);
errorObjectResult.StatusCode = StatusCodes.Status500InternalServerError;
return errorObjectResult;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With