Front-end error monitoring is becoming more and more important in the front-end field. Jquery is not define and Script error are common bugs. In order to give users a better experience, it is necessary to eliminate the probability of front-end error events and improve the stability of the system

Built-in error object

Browsers throw exceptions when code fails to run, such as ReferenceError with undefined variables and TypeError with undefined functions in objects. If no error handling is done, execution of the script is usually terminated. Javascript defines built-in Error objects in 7, including Error, RangeError, ReferenceError, SyntaxError, TypeError, URIError, and EvalError

Error

A generic exception object. We usually use Error to customize exceptions. The Error object has the name and message properties. Message can be used to get specific Error information, such as

Let error = new error (' error '); let name = error.name; // 'Error' let msg = error.message; // 'interface error'Copy the code

RangeError

Out-of-range errors, such as declaring an array of negative numbers, using toFixec that exceeds the number of digits specified for decimals (0-20)

New Array (1) (1.2). The toFixed (21)Copy the code

ReferenceError

Access undefined variables, such as

function foo() { bar++; // bar is not defined}Copy the code

TypeError

Type errors, such as calling a variable as a function when it is not a function

let a = 1; a(); // Type errorCopy the code

SyntaxError

Syntax error, generally out of the code statement is incomplete, such as

let a = 1 > 0 ? // The re is incomplete if (a) {// a semicolon is missingCopy the code

URIError

When using a global URI function, throw if the argument is wrong, for example

encodeURI('\uD800')
encodeURIComponent('\uD800')
decodeURI('%')
decodeURIComponent('%')
Copy the code

EvalError

Calling the eval() function throws an error, for example

eval('3a')
Copy the code

Error handling

We can catch errors with try/catch syntax. The most common is to catch errors in a function and then catch them

function foo () { try { bar(); } catch (e) {console.log(e); console.log(e.message) } }Copy the code

try/catchYou can only catch errors thrown by synchronous code, not asynchronous code

Try {setTimeout(() => {throw new Error('async Error ')}, 0) } catch (e) { console.log(e.message) } // async/await async function foo () { let a = 1; let b = await a + 2; console.log(b); throw new Error('async error') } try { foo(); } catch (e) { console.log(e.message); SetTimeout (() => {try {throw new Error('async Error ')} catch (e) {console.log(e.message); } }, 0) async function foo () { try { let a = 1; let b = await a + 2; console.log(b); throw new Error('async error') } catch (e) { console.log(e.message); } } foo();Copy the code

The downside of this error handling is that it requires a try/catch catch for each function, which requires a lot of repetitive code. You can actually use a global error event to catch all errors

Window. onerror = function(message, source, lineno, colno, error) { Console. log(message + '\n' + source + '\n' + lineno); Return true; // Disable the browser from printing standard error messages. }Copy the code

Window.onerror can catch the above runtime errors and errors thrown by custom and asynchronously, but not Script errors, network exceptions, and promise errors

Network Exception Capture

Network exceptions can be caught in the event capture phase, via window.addeventListener, before the document is loaded

/ / ie11 and mainstream browser window. The addEventListener (' error ', function (e) {e.s topImmediatePropagation (); const srcElement = e.srcElement; If (srcElement === window) {// global error console.log(e.message)} else {// Element error, Log (srcelement.tagname) console.log(srcelement.src); } }, true)Copy the code

Promise error capture

Promise exceptions can be caught in one of two ways

  • Captured by the second argument to the THEN function

  • Catch through the catch function

    let pro = new Promise((resolve, reject) => { console.log(c); // throw c is not defined reject(‘some error happen’); })

Whoever declares the error-catching callback first catches it, but as long as one error-catching function is caught, subsequent error-catching functions are not called

Pro. Catch (err => {console.log(' Catch errors by catch: ${err} '); }). Then (res = > {}, err = > {the console. The log (` in then the second parameter to capture error: ${err} `); }) // Catch errors: ReferenceError: c is not defined pro.then(res => {}, err => {console.log(' ${err} '); }). The catch (err = > {the console. The log (` through catch catch error: ${err} `); }) // Catch an error in the then second parameter: ReferenceError: c is not definedCopy the code

If the Promise instance itself does not do error catching, a global error unhandledrejection is thrown

window.addEventListener('unhandledrejection', function(e) {
  e.preventDefault();
  console.log(e.type)    // unhandledrejection
})
Copy the code

Async/await error catching

Async /await is implemented based on promises and cannot be used in normal callback functions. Async can handle synchronous or asynchronous errors with a try/catch

Function getData() {return new Promise((resolve, reject) => {throw new Error(' Error ')})} try {getData(); } catch (err) {console.log(err) cannot catch an error; } (async function f() { try { await getData(); } catch (err) {// Error console.log(err); }}) ();Copy the code

Script error

If you reference js files from different sources in the outer chain, onError will only raise Script error, which is not accurate to the specified file and line number. You can use the Script tag crossorigin=”anonymous” to set this attribute. Access-control-allow-origin :* response header needs to be set on the server for the static file of the response

<script type="text/javascript" src="http://localhost:3000/test/script.js" crossorigin="anonymous"></script>
Copy the code

This will catch errors in the script.js file, as shown below

Error location of compressed JS

By controlling the script tag crossorigin=”anonymous” can catch js errors in different fields, online code is compressed, can catch errors in the compressed line number and variables, You can use the Source-map module provided by Node to locate the line number of the source file in which the error message is reported

const path = require('path') const sourceMap = require('source-map') const fs = require('fs') const readFile = function (url) { return new Promise((resolve, reject) => { fs.readFile(url, (err, res) => { if (err) { reject(err) } else { resolve(res); }})})} const error = {"message":"Uncaught ReferenceError: a is not defined","source":"http://localhost:3000/dist/index.min.js","line":1,"column":588,"error":"ReferenceError: a is not defined"} console.log(error); Async function getSourceMap(source) {let basename = path.basename(source); let sm = await readFile(path.join(__dirname, './dist/' + basename + '.map')); let smObj = {}; try { smObj = JSON.parse(sm); } catch (err) {console.log(' failed to find source map file ')} return smObj; } async function analyze(errObj) { let rawSourceMap = await getSourceMap(errObj.source); try { await sourceMap.SourceMapConsumer.with(rawSourceMap, null, consumer => { let sourcePos = consumer.originalPositionFor({ line: errObj.line, column: errObj.column }); Object.assign(errObj, sourcePos); return errObj; }); } catch (err) { console.log(err.message); } return errObj; } analyze(error). Then (res => {console.log(res); });Copy the code

The error message reported is line 1, column 588 of the index.min.js file

The parsed error message is located at line 2, column 11 of the SRC /foo.js file

(Foo. js is the module referenced by index.js)

{a good Web front-end developer needs both breadth and depth of knowledge, so many large companies have difficulty recruiting ideal front-end developers even if they pay high salaries. So how to systematically learn enterprise practical Web front-end technology, front-end learning training, video tutorials, learning routes, add prestige: Kaixin666Haoyun contact me. I believe that you will be inspired to find the direction and goal of learning. If you do not understand the front end of the problem, you can continue to pay attention to me, every day will send some front-end related knowledge, for everyone to learn and reference! });Copy the code