Hope
Hope

Reputation: 1292

HttpResponseException

I am facing a big problem for handling errors in MVC 4 webAPI. Here I want to validate incoming request and send back a BadRequest response.

For that i am using the code

public Product GetProduct(int id)
{
    Product item = repository.Get(id);
   if (item == null)
   {
     throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
   }
   return item;
}

But In case of null id, VS2010 will produce another error like

"Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details".

How can i resolve this problem

Thanks in advance....

Upvotes: 5

Views: 23851

Answers (4)

Adrian
Adrian

Reputation: 111

As described in, http://www.asp.net/web-api/overview/error-handling/exception-handling, uncaught/unuser-handled exceptions are translated by default into HTTP responses. Throwing HttpResponseException allows you to specify much of this HTTP response (such as the 404 Not Found status code).

As TrueBlueAussie mentioned, Visual Studio will still break on these exceptions. To disable this:

  1. From the menu, go to DEBUG -> Exceptions...
  2. In the Exceptions dialog, add "System.Web.Http.HttpResponseException" to the Common Language Runtime Exceptions tree.
  3. Uncheck the new System.Web.Http.HttpResponseException's User-unhandled box.

Upvotes: 0

Daru
Daru

Reputation: 150

I would just change the parameter to int? and then do a HasValue check and throw the desired exception. Like this (assuming you want to throw the same exception):

public Product GetProduct(int? id)
{
    Product item;
    if (id.HasValue){
        item = repository.Get(id);
    }
    if (item == null)
    {
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
    }
    return item;
}

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

Your code is actually correct. What you are seeing is Visual Studio's insistence on catching unhandled exceptions (unhandled within your app that is).

HttpResponseException exceptions are handled by the routing that called your Web API and your code will simply generate a 404 error.

Once you install your code on a Web server, it will simply return a 404 error if no matching record exists.

While the suggestion on using a constraint is useful for basic checks, the real use of the 404 is to report that a specific request entry did not exist in the database (rather than did not exist in the URL).

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Use a route constraint to disable null ids: @"\d+". This way the controller action won't even resolve if you don't pass a numeric id in the url and the routing engine will directly return 404.

Upvotes: 2

Related Questions