Home > Software design >  Best practices for error handling in REST apis with async/await?
Best practices for error handling in REST apis with async/await?

Time:06-27

I am making a REST api in my express backend for a messaging app. Right now I'm using a try/catch to handle server side errors:

router.get("/:id", async ({ params }, res) => {
  try {
    const user = await User.findById(params.id);
    if (!user) {
      res.status(400).json({ message: "Invalid User ID" });
      return;
    }
    res.json(user);
  } catch (e) {
    res.status(500).json(e);
  }
});

Would this be fine or is there a better practice I should utilize?

CodePudding user response:

First you should get to know all types of errors:
https://nodejs.dev/learn/error-handling-in-nodejs
https://www.honeybadger.io/blog/errors-nodejs/

You're asking specifically for asych/await with try/catch and I suggest this snippet code from here:

export const catchAsync = (fn) => {
    return (req, res, next) => {
        fn(req, res, next).catch((err) => {
            myConsole(err)()
            setCodeResponse(Code.UNKNOWN_ERROR)
            next(err)
        })
    }
}

and then use it like this:

    requestEdit = catchAsync(async (req, res) => {
    // your code
    })

so you don't need to write try{} catch (){} everywhere.

CodePudding user response:

While all of the answers here are right - its good practice to catch errors and log them in nodejs, you are in fact writing expressjs application running under nodejs environment, and as such you should follow the guide of expressjs of handling errors in endpoints in that library.

Here is a link https://expressjs.com/en/guide/error-handling.html

With this, you dont need any catchAsync from one of the previous answers, you dont even to need to handle most of the errors that might happen in the endpoints code... (Unless you of course want to use them to your leisure (like NotFound errors and proper error code for it)) as the error handler defined for expressjs should handle the errors for you whenever they occure.

CodePudding user response:

Your code is basic, but already nice.

It's good practice, when you catch errors, that you log them somewhere so you can track and fix them over the life of your system. The way you did there, if the error doesn't happen to you, it could be silently affecting users without you knowing.

You can record the errors in any local log or you can also use some online platform (there are several) that offer this service in the form of SaaS.

CodePudding user response:

Your code would be fine for small projects.

If you have alot of checks or try catch block you might want tot consider an error handler. You can forward the error with the next() function. For more info: https://expressjs.com/en/guide/error-handling.html

  • Related