Question

I've got some time to do R&D and have been playing around with OWIN as of today.

I'd like to have an OWIN WebAPI service running for all data interactions, and a separate Web front end SPA project making use of angular.

All code is shamelessly stolen from various random blog posts, and it just for coming to grips with this "new tech".

Startup

  public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            app.UseErrorPage();
#endif

            app.UseWelcomePage("/");
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            app.UseWebApi(config);  

            app.Run(context =>
            {
                if (context.Request.Path.ToString() == "/fail")
                {
                    throw new Exception("Random exception");
                }

                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync("App Init");
            });
        }
    }

AccountsController

public class AccountsController : ApiController
{   
    // GET api/<controller>/5
    public string Get(int id)
    {
        throw new Exception("Random exception");
    }
}

If I navigate to [http://localhost:85/fail] I get a very sexy looking error page.

But when I hit [http://l0calhost:85/api/accounts/5], the error is exposed as json/xml.

  1. Any way to force the API Controller exceptions to use the AppBuilder error mechanism as well?
  2. Would this be frowned upon? (It feels kind of dirty...)
Was it helpful?

Solution

Currently(version 5.0) Web API doesn't have a way to force exceptions happening within it to propagate further down the pipeline. As you have noticed it currently converts exceptions to http response messages having json/xml content. However in the coming release we would be providing this ability as part of our global error handling feature, where you can plugin your error handling mechanism.

IMO seeing an error page for Web API errors is not very useful. If your client is Javascript which is making these calls, then how should this html be displayed?. Also currently browsers have good debugging support where you can trace the calls and figure out issues from the responses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top