Error exception types

try-catch

  1. Basic grammar:
  try{
      console.log(window.a.b)
  }catch{
    console.log(e)
  }
Copy the code
  1. There is a problem
  • Only synchronous errors can be caught, not asynchronous errors, which are not caught
  try{
    setTimeout(()=>{
      console.log(window.a.b)
    },2000)
  }catch{
    console.log(e)
  }
  // Uncaught TypeError: Cannot read property 'b' of undefined
Copy the code
  • Syntax errors could not be caught
  try{
    let name = 'hello world;
    console.log(name)
  }catch{
    console.log(e)
  }
  // SyntaxError: Unterminated string constant
Copy the code

Window. The onError acquisition

  1. Window. onError is a global capture method, which can capture synchronous and asynchronous errors. The captured information is rich, including specific exception information, exception file URL, exception line and column number, and exception stack information. It’s usually written at the beginning of the code
Throw new Error(' =====') window.onerror = function(message, source, lineno, colno, Error) { Error message (string). Can be used for events in the HTML onError ="" handler. * source: script URL (string) * lineno: line number (number) * colno: column number (number) * error: Error object * If this function returns true, it prevents execution of default event handlers, such as exception messages that are not printed on console. When there is no return value or the return value is false, Log ('message',message) console.log('source', source) console.log('lineno',lineno) console.log('colno',colno) console.log('error', error) } // message Uncaught Error: La la la = = = = = / / source/http://localhost:3000/static/js/vendors~main.chunk.js / 25431 / / lineno colno 9 / / the error error: La la la = = = = = an App (App. Js: 5) at renderWithHooks (react - dom. Development. Js: 14985) at mountIndeterminateComponent (react-dom.development.js:17811) at beginWork (react-dom.development.js:19049) at HTMLUnknownElement.callCallback (react-dom.development.js:3945) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994) at invokeGuardedCallback (react-dom.development.js:4056) ...Copy the code
  1. There are two disadvantages. One is that network exception errors, such as static resource loading errors, cannot be caught. The other is that cross-domain scripts cannot catch correct exception information

addEventListener(‘error’)

  1. Listen for JS runtime error events, similar to onError function, but not as rich as onError print information, but can catch network resource loading errors
  2. The third argument to window.addEventListener, useCapture, defaults to false (that is, using event bubblings) or true to event capture
  3. 【 Attention! 】 Be careful if used with window.onerror, as both can catch JS errors
window.addEventListener('error', function(event) { ... }) 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 during the capture phase so if you want to listen globally for resource load errors, you need to catch events during the capture phase // image load failure using the default image, AddEventListener ('error',function(e){let target = e.target, / / the current dom node tagName = target. TagName, count = Number (target. The dataset. Count) | | 0, / / the Number of times in failure, the default is 0 Max = 3; // Total number of failures, If (tagname.toupperCase () === 'IMG'){if(count >= Max){target.src = 'data:image/jpeg; base64,/9j/4AAQSkZJRgABAQEAYABgAAD//AK3/ALYH+5hX6FV5N4Y/5GHwx/vyf+iJa9ZrysPhoYVShDZu/potDmwWFhhIzhT2bv6aLQ//Z'; }else{ target.dataset.count = count + 1; target.src = '//xxx/default.jpg'; } } },true)Copy the code

window.addEventListener(‘unhandledrejection’)

A way to catch asynchronous errors. An unhandledrejection is required for a promise error without a catch that cannot be caught by window.onerror or a try-catch

New Promise((resolve,reject)=>{setTimeout(()=>{reject('not found')})}) window.addEventListener('unhandledrejection',function (err: any) { console.log(err.reason) }) // Uncaught (in promise) not foundCopy the code

The iFrame abnormal

<iframe src="./iframe.html"></iframe> <script> window.frames[0].onerror=function(message, source, lineno, colno, Error) {console.log(' caught iframe exception ',message, source, lineno, colno, error)} </script> Caught iframe exception Uncaught TypeError: Cannot read property 'b' of undefined http://localhost:3000/iframe.html 11 40 TypeError: Cannot read property 'b' of undefinedCopy the code

Crash and jam

Page response is slow and crash, which means JS cannot execute the code in time, crash, that is, JS does not execute. You can use load and beforeLoad of Windows, as well as serviceWorker to start a thread for monitoring

Exception catching capabilities of third-party libraries

  1. Error onError in vue file cannot be caught. In this case, catch the error in the global vue.config. errorHandler
Vue.config.errorHandler = function (err, vm, info) {
    console.log(err)
}
Copy the code
  1. The react of ErrorBoundary

The error boundary is a React component that catches JavaScript errors that occur anywhere in the child component tree and prints those errors while displaying the degraded UI without rendering the child component tree that crashed. Error bounds catch errors during rendering, in lifecycle methods, and in constructors throughout the component tree.

Error message of the interface request

Interface error messages are usually captured in the AXIos interceptor, when the interface code! ==0, or when catch catches an error.

  • To focus on errors caught in catch, sometimes json.stringify is followed by an empty object. This is because the specific error message of error is sometimes not enumerable, so the second argument to json.stringfy is used
    console.log(JSON.stringify(error,Object.getOwnPropertyNames(error)))
    Copy the code

Ii. Processing of errors and exceptions in production environment

sourcemap

1. All error messages reported in production are displayed in the first line because they are compressed in production, and keeping Sourcemap allows you to use the webpack generated.map file to track specific error locations. This, however, exposes the source code to the user, and the recommended way is to use source-map parsing on the server for incoming error messages. 2. Webpack custom plug-in realizes sourcemAP automatic upload