Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

xmlhttprequest - Catching an Access-Control-Allow-Origin error in JavaScript

I wrote a function that keeps returning an Access-Control-Allow-Origin error. This is actually fine for me; I don't want to fix this. I just want to catch it so I can read its message in my program.

All the code that causes the error to be thrown is within my try block, and my catch block displays the error's string message. However, when I run the code, no error is caught, and the error shows up in red in the console. How do I catch this error and store its message?

        try {
            var xhr = new XMLHttpRequest();
            xhr.onload = function() {
                if (this.status < 400 && this.status >= 300) {
                    console.log('this redirects to ' + this.getResponseHeader("Location"));
                } else {
                    console.log('doesn't redirect');
                }
            }

            xhr.open('HEAD', $scope.suggLink, true);
            xhr.send();
        } catch(e) {
            console.log('Caught it!');
            console.log(e.message);
        }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While the browser itself will log a more-detailed error message to the console, you can’t access that from your code. See https://bugs.chromium.org/p/chromium/issues/detail?id=118096#c5:

The details of errors of XHRs and Fetch API are not exposed to JavaScript for security reasons.

As far as the what specs actually require here, the Fetch spec is what defines the details of the “status message” to provide in case of an error — even if the XHR API is used instead of the Fetch API (the XHR spec references the Fetch spec). And for any network error or response blocked by the browser, the Fetch spec requires that the status message be “the empty byte sequence”:

A network error is a response whose status is always 0, status message is always the empty byte sequence, header list is always empty, body is always null, and trailer is always empty.

So all you can get back from any error object you can catch is “TypeError: Failed to fetch” or such.

If you’re using XHR, the only means you have for handling an error is the onerror event handler:

xhr.onerror = function() { console.log("Error occurred but I dunno what exactly.")}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...