Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HttpStatusCode from Exception in WebAPI?

Is there anyway we can get HttpStatus code when exception caught? Exceptions could be Bad Request, 408 Request Timeout,419 Authentication Timeout? How to handle this in exception block?

 catch (Exception exception)
            {
                techDisciplines = new TechDisciplines { Status = "Error", Error = exception.Message };
                return this.Request.CreateResponse<TechDisciplines>(
                HttpStatusCode.BadRequest, techDisciplines);
            }
like image 878
James123 Avatar asked Apr 19 '26 20:04

James123


2 Answers

I notice that you're catching a generic Exception. You'd need to catch a more specific exception to get at its unique properties. In this case, try catching HttpException and examining its status code property.

However, if you are authoring a service, you may want to use Request.CreateResponse instead to report error conditions. http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling has more information

like image 87
neontapir Avatar answered Apr 21 '26 14:04

neontapir


I fell into the same trap when doing error handling in my WebAPI controllers. I did some research on best practices for exception handling and finally ended up with following stuff that works like a charm (hope it will will help :)

try
{       
    // if (something bad happens in my code)
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("custom error message here") });
}
catch (HttpResponseException)
{
    // just rethrows exception to API caller
    throw;
}
catch (Exception x)
{
    // casts and formats general exceptions HttpResponseException so that it behaves like true Http error response with general status code 500 InternalServerError
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(x.Message) });
}
like image 27
theGeekster Avatar answered Apr 21 '26 13:04

theGeekster