Search code examples
mapboxmapbox-gl-jsmapbox-gl

Mapbox GL: How can I handle invalid/expired access tokens?


I've implemented Mapbox GL:

script.src = 'https://api.mapbox.com/mapbox-gl-js/v2.8.2/mapbox-gl.js';
script.onload = function() {
    mapboxgl.accessToken = 'invalid_token';
    map = new mapboxgl.Map({
        container: 'mapsection', // container ID
        style: 'mapbox://styles/mapbox/streets-v11' // style URL
    });
}

If the access token is invalid or expired then a message is shown in the console, but how can I handle this in my code? I've tried both try .. catch and map.on('error'), but neither acknowledge there is an error. Any operations on the map are performed without errors, but there is just nothing to see on the page.

Alternatively, is there an API to validate a given token?


Solution

  • Looks like I was almost there, but just made a small mistake. It is indeed the map.on('error') event handler I need to use:

    script.src = 'https://api.mapbox.com/mapbox-gl-js/v2.8.2/mapbox-gl.js';
    script.onload = function() {
        mapboxgl.accessToken = 'invalid_token';
        map = new mapboxgl.Map({
            container: 'mapsection', // container ID
            style: 'mapbox://styles/mapbox/streets-v11' // style URL
        });
        map.on('error', (response) => {
            alert(response.error.message)
        });
    }