配置号404和500有助于在应用异常时做出更友好的提示,而且可以通过404和500页面上报,监控站点异常。
404页面路由
扩展nuxt.config.js
中的router字段:
<code class="language-null">router: { middleware: ['user-agent'], extendRoutes(routes, resolve) { routes.push({ name: 'custom', path: '*', component: resolve(__dirname, 'pages/error/404.vue') }) } } </code>
500报错页面
500报错页面分为静态报错页面和layouts/error.vue报错页面。
- layouts/error.vue报错页面
虽然此文件放在 layouts 文件夹中, 但应该将它看作是一个 页面(page),这个布局文件不需要包含 <nuxt/>
标签。你可以把这个布局文件当成是显示应用错误(404,500等)的组件。
参考
在页面asyncData中使用try cache捕获报错,并调用context.error展示layouts/error.vue
<code class="language-null">async asyncData ({ params, error }) { try { const { data } = await axios.get(`https://my-api/posts/${params.id}`) return { title: data.title } } catch (error) { error({ statusCode: 404, message: 'Post not found' }) } } </code>
注意在plugins/axios.js中,监听$axios.onError,并调用context.error,并不会展示layouts/error.vue,如果页面中没有try cache这个请求的报错,会直接展示静态报错页面。
- 静态报错页面
定制页面报错信息,扩展nuxt.config.js
中的messages字段
<code class="language-null">messages: { loading: 'Loading...', error_404: 'This page could not be found', server_error: 'Server error', //服务器端报错页面标题 nuxtjs: 'Nuxt.js', //服务器端报错页面左下角文案 back_to_home: 'Back to the home page', server_error_details: 'An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.', //服务器端报错页面左下角文案报错内容 client_error: 'Error', client_error_details: 'An error occurred while rendering the page. Check developer tools console for details.' </code>
}
或者在创建 nuxt工程根目录/app/views/error.html 文件
参考 Change the Nuxt.js server error page
参考 Handling errors while server side rendering your code in Nuxt.js