Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api always returns http status code 200 when an exception occurs

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.

like image 248
Elisabeth Avatar asked Aug 05 '15 18:08

Elisabeth


People also ask

How do I fix HTTP response 200?

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.

How do I return an exception in Web API?

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.

Which of these sends a response HTTP status code 200 to the browser?

OK 200. The request was fulfilled.

Is it OK to return 200 on error?

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.


1 Answers

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);
}
like image 106
Alex Booker Avatar answered Oct 02 '22 22:10

Alex Booker