ESRI JS API Request Catch All

Demo how to catch all request responses and errors

HTML

<script src="//js.arcgis.com/3.12/"></script>
<link rel="stylesheet" href="//js.arcgis.com/3.12/esri/css/esri.css">
<div id="map"></div>

CSS

html, body, #map {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}
body {
    background-color: #FFF;
    overflow: hidden;
    font-family: "Trebuchet MS";
}

JavaScript

// NOTE: this fiddle intentionally throws an error and shows an alert
// you will need to open the console window to see results

var map;

require(["esri/request", "dojo/aspect", "esri/map", "dojo/domReady!"], function(esriRequest, aspect, Map) {
    
    // capture every request (sent through esriRequest)
    esriRequest.setRequestPreCallback(function(ioArgs) {
        var requestUrl = ioArgs.url;
        if (ioArgs.load) {
            aspect.before(ioArgs, "load", function(loadArgs) {
                // now you can inspect the args that will 
                // be sent to the load callback before it is called
                console.log(requestUrl + ' loaded, response: ', loadArgs);
            });
        }
        if (ioArgs.error) {
            aspect.before(ioArgs, "error", function(errorArgs) {
                // now you can inspect the error that will 
                // be sent to the error callback before it is called
                alert('"' + errorArgs.message + '" error when processing ' + requestUrl);
            });
        }
        
        // if you don't return ioArgs, request doesn't work
        return ioArgs;
    });

    // this should fail b/c it tries to process HTML as JSON
    esriRequest({
        url: "/echo/html/",
        content: {
            html: "<p>Text echoed back to request</p>",
            delay: 1
        },
        handleAs: "json",
        load: function(response) {
            // should never reach this line
            console.log('esriRequest response', response);
        }
    }, {
        usePost: true
    });
    
    // initialize map
    map = new Map("map", {
        basemap: "topo",
        center: [-122.45, 37.75], // longitude, latitude
        zoom: 13
    });
});