locked
ExceptionFilterAttribute - returned HttpResponseException is caught by visual studio RRS feed

  • Question

  • User-895552810 posted

    Hi

    In order to get to the bottom of an error I was having in my controller, I created my own ExceptionFilterAttribute and registered it for the controller (as described here: http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling - I'm using the ExceptionHandlingAttribute class posted there).

    Now, if something goes wrong in a controller method, I do get the OnException in my ExceptionFilterAttribute. And then, when I get to the code where the custom error is returned

    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("An error occurred, please try again or contact the administrator."),
                    ReasonPhrase = "Critical Exception"
                });

    Visual studio catches this and informs me that there's an HttpResponseException that's not handled by user code. 

    Of course there is.. this thing is supposed to go to the client. 

    Shouldn't this not pop up as throwing the HttpResponseException at this point is how you're supposed to return something to the client?

    Thursday, April 9, 2015 9:26 AM

Answers

  • User1066278571 posted

    Web API provides an IExceptionHandler. Implement this and handle your exceptions as required.

    https://damienbod.wordpress.com/2014/02/12/exploring-web-api-exception-handling/

    greetings Damien

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, April 12, 2015 4:32 AM
  • User-782957977 posted

    When you  run application from Visual Studio and if there any unhandled exception or any explicitly thrown exception like HttpResponseException in your case, Visual Studio will break. This is the default behavior of Visual Studio  in different type of applications like windows app, console app or web.   This will happen only when you run application from Visual Studio.  If you enter rest url in browser  after hosting in IIS, then your unhandled exception handler (Exception filter)  will catch this exception.

    In case of Asyc methods, visual studio is not breaking because of the difference in exception handling Async methods (https://msdn.microsoft.com/en-us/magazine/jj991977.aspx).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, April 12, 2015 11:21 PM

All replies

  • User-782957977 posted

    I would prefer handling exception in controller if possible and send custom error message. Let exception filter to handle any unhandled exception

    You can try like this

    Controller

    public class CustomerController : ApiController
        {
            public Customer Get(int? id)
            {
                Customer customer = new Customer();
                try
                {
                    if (id.Value > 0)
                    {
                        // Get Cutomer details
                        return customer;
                    }
                    else
                    {
                        customer.ErrorMessage = "Invalid id";
                    }
                   
                }
                catch (Exception ex)
                {
                    customer.ErrorMessage = "Custom error message";
                    //customer.ErrorMessage = ex.Message;
                }
    return customer;
    } }

    Model class

     public class Customer
        {
            public int CustomerId { get; set; }
    
            public string Name { get; set; }
    
            public string ErrorMessage { get; set; }
        }

    Thursday, April 9, 2015 8:19 PM
  • User-895552810 posted

    Hi

    But this means decorating all your data objects with an error which may not always be possible - and isn't one point of using rest that you use the HTTP response codes to tell whomever is using your controller something about the error? E.g. if I don't find a customer (to take your example), in my case, I'd return an http 404 since tthe customer with id so and cannot be found. And I do similar things for adding customers (e.g. duplicate objects). It also means whomever is calling a method on your controller has to look at the response object and its error message to determine if the call was successful or not. I much rather tell the caller immediately with an http response code that something wasn't working out (and that's how thirdparty rest apis I'm using do things).

    In any way - my ExceptionFilter is meant to only catch uncaught exceptions and return something more meaningful than just an HTTP 500 (so I'm using it as suggested). I'm just wondering why visual studio is catching those. It is rather similar than the issue I have with async vs. sync controller methods returning an HttpResponseException.. in async, things work as expected, in sync, visual studio catches the exception. So there seems to be some kind of logic behind that I'm trying to understand.

    Friday, April 10, 2015 12:34 PM
  • User-782957977 posted

    Instead of throwing exception, try following solution. You are not seeing exceptions in Async method because of the difference in exception handling in Async methods.

    public HttpResponseMessage GetProduct(int id)
    {
        Product item = repository.Get(id);
        if (item == null)
        {
            var message = string.Format("Product with id = {0} not found", id);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }
    }

    Friday, April 10, 2015 7:49 PM
  • User1066278571 posted

    Web API provides an IExceptionHandler. Implement this and handle your exceptions as required.

    https://damienbod.wordpress.com/2014/02/12/exploring-web-api-exception-handling/

    greetings Damien

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, April 12, 2015 4:32 AM
  • User-782957977 posted

    When you  run application from Visual Studio and if there any unhandled exception or any explicitly thrown exception like HttpResponseException in your case, Visual Studio will break. This is the default behavior of Visual Studio  in different type of applications like windows app, console app or web.   This will happen only when you run application from Visual Studio.  If you enter rest url in browser  after hosting in IIS, then your unhandled exception handler (Exception filter)  will catch this exception.

    In case of Asyc methods, visual studio is not breaking because of the difference in exception handling Async methods (https://msdn.microsoft.com/en-us/magazine/jj991977.aspx).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, April 12, 2015 11:21 PM