Home > Blockchain >  Exception Handling in ASP.NET Web API giving me errors after HttpRequestException
Exception Handling in ASP.NET Web API giving me errors after HttpRequestException

Time:06-19

So here is one of my actions.

public Customers GetCustomer(int id)
{
    var customer = _context.Customers.SingleOrDefault(c => c.Id == id);

    if (customer == null)
        throw new HttpRequestException(HttpStatusCode.NotFound);
    return customer;
}

This part of the code

throw new HttpRequestException(HttpStatusCode.NotFound);

throws the following error

cannot convert from 'System.Net.HttpStatusCode' to 'String'

Also, in one of my other methods, same error is being thrown on the following.

throw new HttpRequestException(HttpStatusCode.BadRequest);

This is an Api controller and I am not sure why these errors are being thrown. I looked up the syntax on the microsft website and it seems to be correct. It can be seen here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling

CodePudding user response:

I think that you are looking for is HttpResponseException and not HttpRequestException. If so, you can do it as below:

throw new HttpResponseException(HttpStatusCode.NotFound);

This works, because as you can see in documentation, there is a constructor for that class that takes one parameter of type HttpStatusCode. On the other hand, as you can see here, this is not true for HttpRequestException.

  • Related