Catch and handle exceptions to avoid blank screen. So how do you catch exceptions?

Actively catch runtime exceptions

Try -catch is used to catch runtime errors in synchronized code. If it is asynchronous code, convert to await. Such as:

try {
  doSth()
  await doSth2()
} catch (e) {
  // Handle exceptions
}
Copy the code

Handle unexpected global runtime exceptions

The Window raises error events when unhandled JavaScript runtime errors (including syntax errors) occur. Handling exceptions:

window.addEventListener(
  'error'.(e) = > {/* Handle exceptions */})Copy the code

When a resource (such as or

const img = new Image();
img.addEventListener(
  'error'.(e) = > {/* Handle exceptions */}
)
img.src = 'xxx'
Copy the code

Asynchronous code: Processing of Promise Reject

When a Promise is rejected, it can be processed in the second argument to then or catch. Such as:

p().then(onSuccess, onReject)
p().catch(onReject)
Copy the code

If the Promise Reject is not handled, the window will fire the unHandledrejection event. Can be handled uniformly:

window.addEventListener(
  'unhandledrejection'.(e) = > {/* Handle exceptions */})Copy the code

Common handling of interface errors when using Axios

Common handling of interface errors can be added to the interceptor returned by the Axios interface. Such as:

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, a component can be wrapped around the root component to handle errors. Such as:

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

Use:

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

Reference documentation

  • Brief introduction to front-end error handling
  • MDN: GlobalEventHandlers.onerror