Search code examples
javascriptangularjsangular-ui-routeroclazyload

How to handle 404 - resource not found error in ocLazyLoad


I like to know how I could handle resource loading errors in ocLazyLoading. I try to load some resources in the resolve part inside my $stateProvider. There is one file ctrl.js which is available to load. Another file called iam-not-there.js is trying to load but this resource doesnt exist.

Now I would like to handle this "loading" error (proceed with the resolve part even if there is an error in resource loading, handle/catch a resource loading error, and so on...). It just work fine if all my resources are available to load. Once one resource is not able to be loaded the application does not proceed with the resolve state. Here is a plnkr example to reproduce this problem.

var myApp = angular.module("myApp", ['ui.router', 'oc.lazyLoad']);

myApp.config(function($stateProvider, $urlRouterProvider) { 
    $stateProvider
        .state('login', {
            url: '/',
            templateUrl: 'template.html',
            controller: 'LoginController',
            resolve: {
                deps: ['$ocLazyLoad', function($ocLazyLoad) {
                    return $ocLazyLoad.load({
                      name: "myApp",
                      files: [
                        'ctrl.js',
                        'iam-not-there.js'
                      ] 
                    });
                }]
            } 
        });

    $urlRouterProvider.otherwise('/');
});

Solution

  • The error can be caught from a promise, yet loading won't proceed further. It is expected that a list of dependency promises is processed altogether, and loading process won't recover if one of dependencies fails - even if an error is caught from resulting promise.

    Generally it is desirable behaviour, because if a file is required for dependencies to be loaded, it is reasonable that it cannot be considered optional.

    If the file is considered optional indeed, this could be handled explicitly:

    deps: ($ocLazyLoad, $q) => {
      return $q.all([
        $ocLazyLoad.load('iam-not-there.js').catch(err => {}),
        $ocLazyLoad.load({
          name: "myApp",
          files: ['ctrl.js']
        })
      ])
    }