Nuxt句柄从Prism API获取错误



我正在用Nuxt to和Prism作为CMS构建一个博客。

我的nuxt.config.js看起来是这样的:

mode: 'universal',
modules: ['@nuxtjs/prismic'],
target: 'static',
generate: {
fallback: '404.html',
},

Project通过build命令"部署在Netlify上;npm运行生成";

在pages目录中,我有动态链接(_uid.vue(,在那里我使用新的fetch来根据路由获取帖子。

async fetch() {
const post = await this.$prismic.api.getByUID('blog-post', this.$route.params.uid)
this.post = post
},

这一切都有效!然而,我想处理获取错误并显示相应的错误页面。例如,当我们试图获取的帖子不存在或现在被删除时。我试着从我上面提供的关于获取的链接中看到,但我得到了一个错误,那就是帖子是未定义的。

async fetch() {
const post = await await this.$prismic.api.getByUID('blog-post', this.$route.params.uid)

if (post.id === this.$route.params.id) {
this.post = post
} else {
// set status code on server and
if (process.server) {
this.$nuxt.context.res.statusCode = 404
}
// use throw new Error()
throw new Error('Post not found')
}
}

我在GitHub 上的项目

此外,我不确定在页面内使用fetch挂钩是否被视为最佳实践,我认为您应该更喜欢具有以下模式的asyncData(或async/await模式(:

export default {
asyncData({ params, error }) {
return axios
.get(`https://my-api/posts/${params.id}`)
.then(res => {
return { title: res.data.title }
})
.catch(e => {
error({ statusCode: 404, message: 'Post not found' })
})
}
}

从Nuxt文档~

你能不能不抓住这样的异常:

try {
const post = await this.$prismic.api.getByUID('blog-post', this.$route.params.uid);
if (post.id === this.$route.params.id) {
this.post = post;
}
} catch ((error) => {
// set status code on server and
if (process.server) {
this.$nuxt.context.res.statusCode = 404;
}
// use throw new Error()
throw new Error('Post not found');
});

当然,您必须实际检查发生的异常类型。

最新更新