public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new NiceInternalServerExceptionResponse("The current operation could not be completed sucessfully.);
}
}
When a call this Get action:
[HttpGet]
public async Task<IHttpActionResult> Get()
{
Convert.ToInt16("this causes an exception state");
var data = await service.Get();
return Ok(data);
}
An exception is raised... and my global exc handler is triggered.
When my custom response is returned to the client my fiddler always says:
Result: 200
I could also change the return Ok(data);
to return NotFound();
That will not change anything in the result status code.
How can I overwrite/intercept the http status creation and return my own status code 500 instead?
On my web client I need to show a nice error dialog with a logging id + error message ONLY when status code 500 is returned.
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.
OK 200. The request was fulfilled.
HTTP 200 has nothing to do with success or failure of your "business code". In your example the HTTP 200 is an acceptable status to indicate that your "business code error message" was successfully transferred, provided that no technical issues prevented the business logic to run properly.
You need to set the status code on the IHttpActionResult
:
public class NiceInternalServerExceptionResponse : IHttpActionResult
{
public string Message { get; private set; }
public HttpStatusCode StatusCode { get; private set; }
public NiceInternalServerExceptionResponse(
string message,
HttpStatusCode code)
{
Message = message;
StatusCode = code;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(StatusCode);
response.Content = new StringContent(Message);
return Task.FromResult(response);
}
}
And in your GlobalExceptionHandler
pass HttpStatusCode.InternalServerError
(500):
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new NiceInternalServerExceptionResponse(
"The current operation could not be completed sucessfully.",
HttpStatusCode.InternalServerError);
}
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