简体   繁体   中英

How to send Send TypeErros in Chrome console to Alert

Consider a script file with

 let something = undefined;
 let undefined = something.test;

This will throw in the Chrome console:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'test')

How can that error be sent to an Alert to the user, rather than accessing the console?

The two approaches below have been tried with no success - Also wrapping the assignment into a try catch throw.

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
    alert(
      `Error: ` +
        errorMsg +
        ` Script: ` +
        url +
        ` Line: ` +
        lineNumber +
        ` Column: ` +
        column +
        ` StackTrace: ` +
        errorObj
    );
  };

window.addEventListener("error", handleError, true);

function handleError(evt) {
    if (evt.message) { // Chrome sometimes provides this
      alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
    } else {
      alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
    }
}

I though this might be a load order issue, but the function is in a separate script file that is loaded before the file with the incorrect assignment.

You tried try catch? This is working for me.

try {
  let c = undefined.test;
} catch(error) {
  alert(error);
}

Ok I was able to get the window.onerror to work by running it on a localhost server

In one javascript file I defined the following.

window.onerror = function (errorMsg) {
    alert(errorMsg);
};

In another I caused the error with:

let c = undefined.test;

I believe the reason is CORS issue see:

When an error occurs in a script, loaded from a different origin, the details of the error are not reported to prevent leaking information

Running this code on a local python http server shows the full error message in the alert. Let me know if this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM