6
votes
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.

3

3 Answers

1
votes

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);
}
0
votes

I do it like this...

    [HttpPost]
    public HttpResponseMessage Post()
    {
        try
        {
            // Do stuff
        }
        catch (Exception ex)
        {
            // Something went wrong - Return Status Internal Server Error
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }

Works same for a Get.

0
votes

You could use next code for custom error:

return Content(HttpStatusCode.NotFound, "Foo does not exist.");