S
S
Siple2017-07-07 14:07:48
Node.js
Siple, 2017-07-07 14:07:48

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

1 answer(s)
R
RidgeA, 2017-07-07
@Siple

for await - try/catch, for promises - .catch()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question