Nuxt.js Show Error Notification instead of page

Viewed 242

How can I set up my Nuxt application to catch any error from server and only show notification/toast instead of showing a full page? I already search for an example/tutorial about error handling method but only found how to make a custom page only. Thank you

enter image description here

1 Answers

For anyone looking for a solution to this problem - this answer helped me figure it out https://stackoverflow.com/a/66141865/6668871

This is also a useful article on this matter https://masteringjs.io/tutorials/vue/error-handling

Basically, you can create a wrapper component ErrorBoundary and wrap your template in it.

Here's my ErrorBoundary.vue

<template lang="">
   <div class="position-relative">
    <slot></slot>
   </div>
</template>
<script>
export default {
  name: 'ErrorBoundary',
  data: () => ({
    error: false
  }),
  errorCaptured (err, vm, info) {
    this.$axios.post('/api/log-error', {message: err.message, stack: err.stack, info: info});
    this.$toasted.error(err.message, {
      position: 'bottom-right'
    }).goAway(4000);
    return false;
  },
}
</script>

My /layouts/default.vue pseudo code

<error-boundary>
 <my-whole-website-here></my-whole-website-here>
</error-boundary>

I've implemented error logging to server by axios call. It also shows a toast containing the error message. Note the return false; at the end of this hook, this allows to skip the default error handling thus preventing the redirect to error page.

Related