Answer the question
In order to leave comments, you need to log in
How to catch errors in node.js?
Hello.
How to correctly catch user errors in order to render a 404(ctx.render('404')) page, for example, the user refers to a news item whose id does not exist. And also how to catch system errors, for example mysql has stopped working.
I use Koa2 + mysql
Code snippet:
// Models/Post.js
const Database = require('../Configs/Database')
exports.findBySlug= async (slug) => {
let [post] = await Database.execute('SELECT * FROM posts WHERE slug= ?', [slug])
return post[0]
}
// Controllers/PostController.js
const Post = require('../Models/Post')
Class PostsController {
async index(ctx) {
let post = await Post.findBySlug(ctx.params.slug)
await ctx.render('post', { post })
}
}
module.exports = new PostsController()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question