DEV Community

Mazen Ramadan
Mazen Ramadan

Posted on • Edited on

Different methods for handling errors in Express

It gets confusing sometimes when you have to deal with errors in different methods. In this post I will discuss different methods for handling errors in Express.js and when to use each of them.

Why do we need to handle errors anyway ?

  • Not all of users know that might be something wrong with their inputs, they might just think that the service is down.
  • It lets the user know, in a relatively friendly manner, that something has gone wrong and that they should change how they behave.
  • it allows the programmer to put in some niceties to aid in the debugging of issues.
  • Some errors leads the server to crash down.

Now I will use the same function in every method so the difference between each will be clear.

The function is simple, it is an API that POST data into the database.

router.post('/article', async (req, res) => {
  title = req.body.title
  content = req.body.content
  const newPost = await new Post({
    title: title,
    content: content
  })
  newPost.save()
  res.status(201).json(newPost)
})
Enter fullscreen mode Exit fullscreen mode

Now this code works great ONLY if the user used it in a correct way, if he didn't provide any content or title the server will crash. of course we don't need this!


1- Using Try-Cath statement

This is the most popular one and you probably figured it out

router.post('/article', async (req, res) => {
    title = req.body.title
    content = req.body.content
    try {
        const newPost = await new Post({
            title: title,
            content: content
          })
          newPost.save()
          res.status(201).json(newPost)
    } catch (err) {
        console.log(err)
        res.status(400).json({"Something went wrong":err.message})
    }
})
Enter fullscreen mode Exit fullscreen mode

In this method we TRY to do whatever the function should do, if there any errors the CATCH statment will catch it then we will return it to the user with the status code of 400 "bad request" and the message of the error so he can know what he had done wrong.

2- Using promises in functions

Most of functions in express are promises that takes arguments like the .save() the function we use here.
We can get the error if any by getting the error in a param like this .save((err)) Here we catch the error and we can make use it like this.

router.post('/article', async (req, res) => {
    title = req.body.title
    content = req.body.content
    const newPost = new Post({
        title: req.body.title,
        content: req.body.content
    })
    newPost.save((err) => {
        if (!err) {
            res.status(201).json(newPost)
        } else {
            console.log(err)
            res.status(400).json({
            "Something went wrong":err.message})
        }
    })
})
Enter fullscreen mode Exit fullscreen mode

Here we check if we don't have any errors with (!err) if we have any we handle it like before.

3- Using promises

router.post('/article', async (req, res) => {
    title = req.body.title
    content = req.body.content
    const newPost = new Post({
        title: title,
        content
    })
    newPost.save()
    .then (result => {
        res.status(201).json(newPost)
    })
    .catch(err => {
        console.log(err)
        res.status(400).json({"Something went wrong":err.message})        
    })
})
Enter fullscreen mode Exit fullscreen mode

This is so similar to try-catch but here we are using promises.

4- Using custom methods

In this method we check or errors that we know that it could happen often so we handle it in a very custom way example of this is when you try get a an article and you know that user might try to get a article that doesn't exist so you handle this error specifically. In this example we will we assume that the user doesn't provide a content or a title in the body of the request.

router.post('/article', async (req, res) => {
    title = req.body.title
    content = req.body.content
    if (!content || !title) {
        res.status(400).json({
        "error":"You must provide content and title"})
    }
    // Rest of the code with any method we used
})
Enter fullscreen mode Exit fullscreen mode

In this example we check if the user didn't provide content or title with the if statement (!content || !title) this will tell the user that they need to provide content and title.

Conclusion

You can use any method of there is no big difference it's just personal prefare.

You can visit the docs of error handling in express docs page for more info.
If you liked the article you can support me with a like.

Top comments (0)