8
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 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I already had the Nice..class implemented and did that: var response = new HttpResponseMessage(); I just did not pass the status code ;-) Thanks and it worked!
@Elisabeth Oh, awesome. If this answer answered your question then please consider marking it as accepted :)
btw. I am confused, what do you mean with your last paragraph:"I cannot discern..." ? Should I change something or you see something bad? What I meant is when a status code 500 is returned to my html client it shows a general error dialog with the id of the logged exception. When a 204 /200 whatever is returned then of course this dialog is not shown. I hope its more clear now?
@Elisabeth I meant I did not understand that part of the question but it does not matter - I removed that part from my answer. I am curious as to why this was downvoted...?
0

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.

6 Comments

I do not catch exceptions in an action as this is a cross cutting concern and should be integrated with the web api pipeline as I did with the global exception handler.
@Elisabeth You should still throw exceptions in action methods, thus global exceptions are mostly used for logging purposes. How would you validate parameters and throw exceptions when argument is null, not formatted etc?
@Teomanshipahi If I understand you correctly: When an invalid parameter is passed then my generic model validation is executed in an Action Filter which returns an BadRequest (400). No need for throwing an exception. There is never a need to throw an Internal Server Error exception. They just happen and get logged not more. If you want to catch and handle business exceptions happening inside an action then use Exception Filters and return the appropriate response.
@Teomanshipahi I know that link. And all I said is inside that link. I would not throw a "throw new HttpResponseException(HttpStatusCode.NotFound);" inside an action. If a resource is not found in the Repository then the Repository has to throw a ResourceNotFoundException which is caught inside the ExceptionFilter.
@Elisabeth Not agree on this. Responsibility of repository is CRUD to data source. It should catch and throw exception related to data. (Db connection, stored procedure exceptions etc..) If repository did not find a result (which is not an exception), it returns null or empty list, and (Web API) throws exception as content not found. You just pass all your exceptions into one field for all your purposes which does not smell good to me.
|
0

You could use next code for custom error:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.