Home > Mobile >  Object is possibly null even with the guard check
Object is possibly null even with the guard check

Time:10-16

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

 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});
    });

CodePudding user response:

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) {
  • Related