Select to view content in your preferred language

How to handle layer errors

2209
1
03-28-2018 03:47 AM
KevinHaeni
Occasional Contributor

Hello,

In JSAPI 3.x, it was possible to react to layer errors, like for example if the map service is not available, with the following code:

this.layer.on('error', function(evt) {
    if (evt.error.code === 400) {
      this.notificationService.error('Layer Error', `Message: ${evt.error.message}`);
    }
}

With layer being a FeatureLayer object.

I don't really see how this can be achieved using JSAPI 4.x. Any ideas?

Tags (1)
0 Kudos
1 Reply
KenBuja
MVP Esteemed Contributor

In one of my projects, I had a list of layers to add. This was the code I used to see if each service was available before attempting to load them.

var promises = [];
array.forEach(layersToAdd, function (layer) {
  promises.push(testService(layer));
});

var allPromises = new all(promises);
allPromises.then(function (response) {
  response.forEach(function (r) {
    if (r.resolution) {
       //load layer
    }
  });
});

    function testService(layer) {
        var deferred = new Deferred();
        var request = new XMLHttpRequest();
        try {
            request.open("get", layer.url + "?f=json");
        }
        catch (error) {
            console.error(error);
            deferred.resolve({ layer: layer, resolution: false });
            return deferred.promise;
        }
        request.onloadend = function () {
            if (this.status !== 200) {
                console.log("Could not load " + layer.name);
                deferred.resolve({ layer: layer, resolution: false });
            } else {
                var response = JSON.parse(this.response);
                if (response.error) {
                    console.log("Could not load " + layer.name);
                    deferred.resolve({ layer: layer, resolution: false });
                } else {
                    deferred.resolve({ layer: layer, resolution: true });
                }
            }
        };
        request.send();
        return deferred.promise;
    }