• Handling WebAPI exceptions with Angular http interceptor

    Handling WebAPI exceptions with Angular http interceptor

    It’s good to return meaningful HTTP status codes upon server exceptions. Whether it be invalid model state, conflict upon trying to create/update an object in the database, unauthorized access or something else it adds additional value and sends a message – one that’s different from generic 400’s or 500’s. These messages can then be used to take certain kinds of actions on the client side based on what happened.

    For example you could register a custom ApplicationExceptionHandler.cs inside your WebApiConfig.cs which would then be able to catch and handle any kind of exception thrown by lower server layers (such as business layer or the DB/ORM layer):

    You need to register ApplicationExceptionHandler in WebApiConfig.cs like this:

    You can also use something like ValidationFilter to take care of invalid model states in an easy way (by replying with a 422). After you have all your desired/needed exception handlers in place, it’s time to setup the client side. You can easily intercept every HTTP request and act upon responses from the server with an http request interceptor that looks like this:

    Now you have a centralized way to handle all kinds of WebAPI errors. Simply build upon this infrastructure and add whatever else you might need. In one of the future posts I’ll explain how to create basic html input element directives (for text, textarea, number, datetime and similar fields) which also seamlessly take care of modelState error messages by presenting them to the user just below the input element.

  • Invalidating Angular template cache with .net BundleConfig.cs

    Invalidating Angular template cache with .net BundleConfig.cs

    You most probably had the problem with old Angular templates not clearing themselves up from the browser cache in production which can cause various problems. If you’re using gulp, you can use something like gulp-angular-templatecache to tackle this problem (which would also be a preferred way of doing this) but if you’re using .net’s BundleConfig.cs to bundle your scripts, you’ll have to add a bit of code to your app.

    Say your app bundle section inside BundleConfig.cs looked something like this:

    Then you would include that inside your index.cshtml (or some other Razor template) like this:

    And this is how the generated HTML script include tag would look in production:

    <script src=”/bundles/my-app?v=6XgTJerMdBNglpDE1l_sgb9JgKJDXS35tee8zasXvLk1″></script>

    What changes upon every deploy is the “v” (version) hash at the end of bundle link. We can leverage that to keep track of the current version by extracting and storing that value within a cookie. Then on a full page reload (F5) if the version hash changed – we can simply clear the template cache and let the user continue using the app. The app will then have to re-cache all the templates once they are requested by the router or a directive.

    That piece of logic can be stored inside app.js on MyApp.run(). Here is how I did it:

    NOTE: I use lodash in every project so if you’re not using it, you might have to write your own code to replace _.find() and _.contains()

  • Resolving Angular $http promises in services vs. controllers

    Resolving Angular $http promises in services vs. controllers

    For some time now I’ve been asking myself one thing when it comes to resolving $http promises in Angular – “would it be a better practice to resolve them in services that make the calls or in controllers that call these services?”. I always simply went with whatever was the practice on the current project as I didn’t want to introduce inconsistencies into the project. Well I finally set down, played around with it a bit and gave it some active thinking. Turns out, the answer is hugely dependent on the context and there is no right or wrong way to do it but I’ll explain how I decided to do it from now on.

    This post is not about basic usage of $http, then, success, error, callbacks or promises in general. For that I recommend a very nice blog post by dwmkerr.

    Now, one “sub”-question I had here was should I use then or success. Although I noticed a lot of people seem to dislike using success and error callbacks because their signatures are inconsistent with the then callback (they are only a thin wrapper around it), I actually find it very useful that I don’t have to extract the “data” from the response object on my own. If I need to do something like that I still have the option of falling back to using then (which is fine). Some people seem to be really bothered by this so they even go as far as to wrap their responses in new promises using $q to match the then signature, but as Rick Strahl wrote – in this case I don’t really mind trading a bit of inconsistency for simplicity. I don’t see a point in adding additional chunk of wrapper-code to every API call just for the sake of it. So, I decided to go with the success/error combination.

    Back to the main question.. I never make any $http requests directly from controllers and along with any additional “client-side business logic”, that code goes into services. As a rule of thumb, I decided to go with a very simple approach. Since most often what happens after the success callback kicks in is controllers concern, my services return $http promises. Success promises are then resolved from within controllers. If there really is a need (and if it’s logical) to resolve the success callback in the service i will then do it there instead. The whole thing looks something like this:

    Now you’re probably wondering – what about the error callbacks? I could think of a couple of different scenarios of what could go wrong here:

    1. Unhandled exceptions
    2. 404’s
    3. “Expected exceptions” such as unauthorized (401), forbidden (403) or anything else you might knowingly return from the back-end
    4. Back-end model validation (I decided to go with 422 for this)


    To make my life easier, for the first three I decided to go with an http-interceptor-service which is in charge of handling WebAPI exceptions. This way I don’t have to rewrite the same error callback code for every $http request. It’s nice, centralized and provides enough flexibility (assuming you’re taking good care of your WebAPI and return proper http statuses).

    As for the last, fourth case, I created a couple of directives that wrap html input elements (text, textarea, dropdown..), WebAPI model state and validation messages (which have the format of foundation abide). For this to work, model state is needed inside a controller and since $http treats 422 status code as an error so far this was the only situation where I had to resolve the error callbacks inside controllers. In this case the http interceptor simply skips any 422 it encounters and it can then be taken care of elsewhere. I will explain this in more detail in my next-next post. Pinky swear. ;)

    The explained might not be the best way to cope with the whole problem but I it worked well for me so far so I hope I was at least able to provide a couple of useful ideas. I did try to google out other blog posts / SO threads about this but I only found a few ones that dealt with something similar but not entirely. If you know of any good ones, please feel free to drop a link down in the comments. Also, if you have a different approach which works for you or you see any problems with mine, do let me know! :)


Back to top