Front-end exception/error handling

Error handling is essential to any front-end. Anyone can avoid writing code will be a bug, and a lot of bugs nor test cases can completely cover, if we don’t have a complete error handling and error collection system, we can know we have a bug, not only that, a lot of bugs may not is a question of front end, such as an interface to return the data format is wrong or less field, Or a particular browser, and so on. With error handling and collection, we are better able to undo this problem through the error stack.

What errors need to be handled

  • JS syntax error, code exception
  • Request error
  • Static resource loading is abnormal
  • Abnormal Promise
  • The Iframe abnormal
  • Cross-domain Script error
  • Page crashes and freezes

Try Catch

Try-catch can only catch synchronous runtime errors, but not syntactic and asynchronous errors.

1. Synchronization runtime error

try { let name = 'foo'; console.log(nam); } catch (e) {console.log(' catch exception: ', e); }Copy the code

Exception caught: 'ReferenceError: nam is not defined at <anonymous>:3:15'

2. Grammar errors

try { let name = 'foo console.log(nam); } catch (e) {console.log(' catch exception: ', e); }Copy the code

Uncaught SyntaxError: Unexpected identifier

3. Asynchronous error

try {
  setTimeout(() = > {
    undefined.map(v= > v);
  }, 1000)}catch (e) {
  console.log('Exception caught:', e);
}
Copy the code

Uncaught TypeError: Cannot read property ‘map’ of undefined

As you can see, try/catch does not catch an asynchronous error

window.onerror

When a JS runtime error occurs, the window raises an error event from the ErrorEvent interface and executes window.onerror().

/ * * *@param {String}  Message Error message *@param {String}  Source Error file *@param {Number}  Lineno line number *@param {Number}  Colno column number *@param {Object}  Error Error Error object (object) */
window.onerror = function(message, source, lineno, colno, error) {
  console.log('Exception caught:', { message, source, lineno, colno, error });
}
Copy the code

Access-control-allow-origin :* response header, access-Control-allow-origin :* response header And add the Crossorigin attribute when referencing the associated JS file. Related articles

In practical use, onError is mainly used to catch unexpected errors, while try-catch is used to monitor specific errors in predictable situations. The combination of onError and try-catch is more efficient.

window.addEventListener

When a resource (such as an image 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 Windows, but (at least in Firefox) can be caught by a single Window.addeventListener.

<img src="./foo.png">
<scritp>
window.addEventListener('error'.(error) = > {
  console.log('Exception caught:', error);
}, true)
</script>
Copy the code

Promise Catch

Errors thrown in promises without a catch cannot be caught by onError or try-catch, so it is important to remember to include a catch in a Promise to handle exceptions thrown.

Or you can add a global listener on unhandledrejection to listen for Uncaught Promise errors globally. Usage:

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

Async /await exception catch:

In fact the async/await syntax is essentially a Promise syntax.

The difference is that async methods can be caught by a superimposed try/catch.

Of course, if you use a library like Axios, error handling can be done in its request instance. Be more flexible.

VUE errorHandler

Vue.config.errorHandler = (err, vm, info) = > {
  console.error('Error caught via vue errorHandler');
  console.error(err);
  console.error(vm);
  console.error(info);
}
Copy the code

React Exception catching

componentDidCatch(error, info) {
  console.log(error, info);
}
Copy the code

Build an exception monitoring system from 0 to 1

Building a systematic front-end anomaly Monitoring System from scratch: related articles