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

Time:06-24

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:

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