• 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.

  • Handling .net’s model state with ValidationFilter attribute

    Handling .net’s model state with ValidationFilter attribute

    This is a simple ValidationFilter class which you can attach to any .net controller action method:

    What it provides is a “one-line” way to handle invalid model states. For example – instead of doing ModelState.IsValid check on each POST/PUT action, and then handling it manually again and again (by basically copying and pasting the same chunk of code all around your controllers) you can simply reuse the [ValidationFilter] attribute in front of your action and it will check whether the ModelState is valid. If it is, the action method will execute whatever code it has inside of it, and if it’s not the WebAPI will respond with a 422 (Unprocessable Entity) together with the associated ModelState error messages.

    For example if you had this model/action combination:

    …and you didn’t send any data to the WebAPI in your POST request, this is the 422 response that you would get back:

    This response can then be further parsed/handled by the client-side without problems.

  • Diving into Gulp

    Diving into Gulp

    For some time now I’ve been waiting to learn how to Gulp properly. As I started working on a home pet-project to keep sharp and get more in-depth with certain things, this was a good opportunity to learn more about Gulp as well. So far, I have mostly been using either famous-ish premade gulp scripts or the tools that came built-in (or as an extension) with Visual Studio. But that never really felt right, more like a cheap get-away.

    Anyway, I went through JavaScript Build Automation With Gulp.js. It’s a Pluralsight ~5hr course by John Papa who is quite a famous name within Angular circles for his angular-styleguide. I loved every bit of the course. It’s easy to follow, goes through the whole setup, explains the how’s and why’s and gives you code samples. I highly recommend it as it will give you a very solid gulp foundation and will make you more productive.

    Right now I’m in the middle of bootstrapping his gulp-patterns, and I’m taking out the stuff that I don’t need. Great base, and I feel very happy about the whole thing. :)

  • 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! :)

    Cheers!

  • Enhancing RESTful WebAPI controllers with RPC style endpoints

    Enhancing RESTful WebAPI controllers with RPC style endpoints

    During the setup stage of the new project I’m working on, the decision was made to try and use RESTful WebAPI controllers that would support RPC style endpoints as well. I did a bit of research and found a nice post from Carolyn Van Slyck that explains how this can be achieved by creating a few different routing rules in the WebApiConfig file. I wasn’t however fully satisfied with this approach so I tried to do it in a different way.

    If you follow .net’s WebAPI conventions, you can simply write action methods that start with http verbs (GET, POST, PUT, DELETE) and everything will work out of the box with the default WebApiConfig setup. For example you can name your RESTful action methods something like GetAllProducts, GetProduct, PostProduct, etc… No extra action route attributes (such as RoutePrefix, Route, HttpGet/Post/Put/Delete) are needed for this approach. WebAPI will in this case expect the correct http verb.

    However, as soon as you add a custom action, it will start causing problems (you will start getting the infamous “Multiple actions were found that match the request” response). Say you add CustomGetEndpoint method – this will cause GetAllProducts and GetProduct to not work any more. Luckily by adding a few things we can make it work.

    The first step is to enable attribute routing in your WebApiConfig:

    The second step is to add the RoutePrefix to your controller and to add the Route and http verb attributes to all your custom RPC actions (they of course don’t have to start with “custom” but you can name them whatever you want):

    In this case ProductModel is very simple:

    Keep in mind that if you are using a BaseApiController class which inherits .net’s ApiController, ensure that all your methods are protected. If you make your BaseApiController methods public, this will mess up the routing and you will start getting the “Multiple actions were found that match the request” response (took me long enough to figure that one out!).

    That’s all folks, you can now enjoy both worlds at the same time. Enjoy!

Back to top