Summary of front-end exception handling methods

Take the initiative to capture

try-catch

   try {
       doSomething()
   } catch (error) {
       log(error)
   }
Copy the code

Handle global running exceptions

Window raises an error event that is not handled by JS:

window.addEventListener(
    'error'.(e) = > {
        log(e)
    }
)
Copy the code

Error was raised when resource loading failed. Procedure

const img = new Image()
img.addEventListener(
    'error'.(e) = > {
        log(e)
    }
)
Copy the code

Asynchronous code

let promise = new Promise()
promise().then(res, rej)
promise().catch(error)
Copy the code

If the promise is not handled, the window will trigger the unHandledrejection event

window.addEventListener(
    'unhandledrejection'.(e) = > {
        log(e)
    }
)
Copy the code

An interceptor using the AXIos interface can handle this

axios.interceptors.response.use(function (response) {
  return response;
}, err= > {
  // Error handling
  if(err.response) {
    switch (err.response.status) {
      case 400: err.message = 'Request error (400)'; break;
      case 500: err.message = 'Server error (500)'; break;
      // ...}}return Promise.reject(error);
})
Copy the code

Exception handling of vUE

app.config.errorHandler = (err, vm, info) = > {
    // Handle exceptions
}
Copy the code

React exception handling

React’s life cycle function ComponentDidCatch catches exceptions for child components. Therefore, you can wrap a component around the root component to handle errors.

class ErrorBoundary extends React.Component {
    componentDidCatch (error, info) {
        // Handle exceptions
    }
}

<ErrorBoundary>
  <App />
</ErrorBoundary>
Copy the code