JS abnormal

plan describe
window.onerror Developer.mozilla.org/zh-CN/docs/…
window.addEventListener(‘error’) Developer.mozilla.org/en-US/docs/…

window.onerror

Static resource errors cannot be caught because when a resource (such as <img> or <script>) fails to load, the element that loaded the resource raises an error Event in the Event interface and executes the onError () handler on that element. These error events do not bubble up to the window.

Wrong type describe
EvalError An error related to eval(). Eval () itself is not executed correctly
RangeError A numeric variable or parameter is outside its valid range. Var a = new Array(-1);
ReferenceError Syntax error. Example: var a =;
TypeError A variable or parameter is not in a valid range. Example: [1, 2]. The split (‘. ‘)
URIError Invalid argument passed to encodeURI or decodeURl(). Example: decodeURI (‘ % 2 ‘)
AggregateError This object represents an error when multiple errors need to be wrapped in a single error; When multiple errors are thrown that need to be reported by an operation, such as promise.any (), all promises passed to it are rejected.
InternalError Create an instance of an exception thrown that represents an internal error in the Javascript engine. For example: “Too many recursions”. Non-ecmascript standard.
DOMException Interfaces represent exception events (called exceptions, exceptions) that occur when invoking methods or accessing Web API properties

RangeError

Window. onerror = function(message, source, lineno, colno, error) {console.log(' error message (string) : ',message); Console. log(' error script URL: ',source); Console. log(' error line number: ',lineno); Console. log(' error column number: ',colno); Console. log('Error object: ', Error); } var a = new Array(-1);Copy the code

DOMException

Window. onerror = function(message, source, lineno, colno, error) {console.log(' error message (string) : ',message); Console. log(' error script URL: ',source); Console. log(' error line number: ',lineno); Console. log(' error column number: ',colno); Console. log('Error object: ', Error); } var node = document.querySelector('#app'); var refnode = node.nextSibling; var newnode = document.createElement('div'); node.insertBefore(newnode, refnode);Copy the code

Abnormal Promise

The promise will throw an exception that window.onerror will not catch. Use window.addEventListener(‘unhandledrejection’).

window.addEventListener('unhandledrejection',function(promiseRejectionEvent){
  console.log(promiseRejectionEvent.reason)
})
const p1 = new Promise(function(resolve,reject){
  resolve(a+b);
});
p1.then(function(value){
  console.log(value)
})
Copy the code

console.error

In some scenarios, you also need to catch console.error exceptions for business systems

Window.console. error = function(){console.log(' console.error caught,arguments :',arguments); consoleError && consoleError.apply(window,arguments); } console.error(' This is a console.error exception ')Copy the code

Abnormal framework

Vue exception capture

app.config.errorHandler = function(err, vm, info) {
  console.log(err, vm, info, "---a00-----");
};
Copy the code

Static resource exception

When a resource (such as <img> or <script>) fails to load, the element that loaded the resource raises an error Event in the Event interface and executes the onError () handler on that element. These error events do not bubble up to the window, but can be caught by window.addeventListener during the capture phase. So useCapture must pass true to catch static resource exceptions.

window.addEventListener('error',function(event){
  console.log(event,'event');
},true)
Copy the code

Cross-domain script error

When a syntax error occurs in a Script loaded from a different domain, to avoid information leakage (see Bug 363897), details of the syntax error are not reported and are replaced with a simple “Script error.”.

In some browsers, this behavior can be overridden by using the Crossorigin attribute in <script> and requiring the server to send the appropriate CORS HTTP response header. One workaround is to handle “Script Error.” separately, telling you that the details of the error are viewable only from the browser console.

Abnormal interface

If the interface is abnormal, the back end can intercept the interface and handle it. The front end does not list the solution.

Problems need to be solved

Now the front end of the project, if once published online, code tends to confuse, compression and encryption, report line mistake, positioning to the line number is 1, such as the following examples, in this way, we monitor to the wrong data, there is no meaning, need to solve this problem, the ideal result is able to pinpoint how many rows into a file, how many columns

The solution

To introduce the source – the map package

var fs = require('fs'), path = require('path'), sourceMap = require('source-map'); / / to parse the map file path. / test/vendor. 8 b1e40e47e1cc4a3533b. Js. Map var GENERATED_FILE = path. Join ('. ', 'dist/js', 'app.5025c1aa.js.map') let getSource = async()=>{ Var rawSourceMap = fs.readFilesync (GENERATED_FILE).toString(); var rawSourceMap = fs.readfilesync (GENERATED_FILE).tostring (); / / object by converting sourceMap library sourceMapConsumer var consumer = await new sourceMap. SourceMapConsumer (rawSourceMap); / / incoming to find number, before compression to find the source file and line number var. Sm = consumer originalPositionFor ({line: 1, / / the number of rows after compression column: 224607 / / compressed columns}); Console. log(' row number of source files: ',sm) // List of all source files before compression var sources = consumer.sources; Var smIndex = sources.indexof (sm.source); var smIndex = sources.indexof (sm.source); Var smContent = consumer.sourcesContent[smIndex]; Const rawLines = smcontent.split (/\r?) const rawLines = smcontent.split (/\r? \n/g); Log (rawlines.join ('\n'))} getSource();Copy the code

According to the source-map file, you can locate a row in a specific file or an error in a column. The problem has been solved.