Amplify.js & ASP.NET Web API: Getting the error message

I’m still learning my way around ASP.NET Web API and have started using Amplify.js in my web apps to consume my web services. I originally learned about Amplify.js from John Papa’s excellent Pluralsight course, “Single Page Apps with HTML5, Web API, Knockout and jQuery”.

Today I noticed that when a server-side error occurs, I was not getting the JSON response that contains the error information in my client-side Amplify error() function (see “Exception Handling in ASP.NET Web API” for an explanation). Taking a look at the Amplify source code revealed that, “out of the box”, Amplify always sends null to the error callback function’s data parameter.

To override this behavior, I created a custom decoder that would use the XHR responseText to feed the error callback data parameter, like so:

amplify.request.decoders.mydecoder =
        function (data, status, xhr, success, error) {
            if (status === "success") {
                success(data, status);
            } else if (status === "fail" || status === "error") {
                try {
                    error(JSON.parse(xhr.responseText), status);
                } catch(er) {
                    error(xhr.responseText, status);
                }
            }
        };

Now I’m able to read the Message property and any other information returned from Web API when a server-side exception is thrown.