Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object is possibly null even with the guard check

Hello I have a problem I am getting the Object is possibly "null" probably because I handle this check by the generic error handler in nodejs + express. How can I solve it?

REST API

export const getOrderRaport = async (
  req: Request<{}, {}, IAuthUser>,
  res: Response,
  next: NextFunction,
) => {
  const orderId = req.query.orderId;
  const order = await Order.findOne({ orderId: orderId });
  if (!order) next(createError("Order does not exist"));
  const orderUser = await User.findOne({ userId: order.userId });
  const requestUser = await User.findOne({ userId: req.body.userId });
  if (!orderUser) next(createError("Order was not found for the specified user"));
  if (!requestUser) next(createError("You are not allowed to view this order"));
  if (orderUser._id != requestUser._id) {
  }
};

error handler

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 app.use((error: CustomError, req: Request, res: Response, next: NextFunction) => {
      const status = error.status || 500;
      const message = error.message || 'Something went wrong';
      res.status(status).json({message});
    });

>Solution :

A "guard check" or guard clause should exit the function/block early so that execution doesn’t move on to the next line. This can be done using either return or throw (or continue/break in loops).

if (!order) next(createError("Order does not exist"));

Should be:

if (!order) return next(createError("Order does not exist"));

To return the next() result from getOrderRaport() (wrapped in a promise).

Or:

if (!order) {
  next(createError("Order does not exist"));
  return;
}

To return undefined as the promise result.

Alternatively you can reject the promise returned from getOrderRaport() by throwing an error, which also halt execution of any further lines in the function.

if (!order) {
  next(createError("Order does not exist"));
  throw new Error("Order does not exist");
}

The same applies for orderUser and requestUser. The following line will crash unless you exit early when those variables are null.

if (orderUser._id != requestUser._id) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading