简体   繁体   中英

How do i fix the node UnhandledPromiseRejectionWarning

When a try to send a simple json including the id of a provider and a date I get the following error

UnhandledPromiseRejectionWarning: TypeError: Cannot
convert undefined or null to object
    at Function.keys (<anonymous>)
    at Function.findAll (C:\Users\Usuario\Desktop\Studies\Go_Stack\modulo2\goBarber\node_modules\sequelize\lib\model.js:1692:47)
    at Function.findOne (C:\Users\Usuario\Desktop\Studies\Go_Stack\modulo2\goBarber\node_modules\sequelize\lib\model.js:1924:17)
    at store (C:\Users\Usuario\Desktop\Studies\Go_Stack\modulo2\goBarber\src\app\controllers\AppointmentController.js:28:63)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:19212) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19212) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


import * as Yup from 'yup';
import { startOfHour, parseISO, isBefore } from 'date-fns'; 
import User from '../models/user';
import Appointment from '../models/Appointment';


class AppointmentController {
    async store(req, res) {
        const schema = Yup.object().shape({
            provider_id: Yup.number().required(),
            date: Yup.date().required(),
        });

        if (!(await schema.isValid(req.body))) {
            return res.status(400).json({ error: 'Validations Fails' });
        }

        const { provider_id, date } = req.body;

        const checkIsProvider = await User.findOne({
            where: { id: provider_id, provider: true },
        });

        if (!checkIsProvider) {
            return res.status(400).json({ error:'You can only create appointments with providers' });
        }

        const hourStart = startOfHour(parseISO(date));

        if (isBefore(hourStart, new Date())) {
            return res.status(400).json({ error: 'Past dates are not permitted' });
        }

        const checkAvailability = await Appointment.findOne({
            where: {
                provider_id,
                canceled_at: null,
                date: hourStart,
            },
        });

        if (checkAvailability) {
            return res.status(400).json({ error: 'Appointment date is not available' });
        }

        const appointment = await Appointment.create({
            user_id: req.userId,
            provider_id,
            date,
        });

        return res.json(appointment);
    }
}

export default new AppointmentController();

findOne method in Appointment class raises exception and you do not catching it anywhere. You need to do something like that:

let checkAvailability;
try {
  checkAvailability = await Appointment.findOne({
    where: {
      provider_id,
      canceled_at: null,
      date: hourStart,
    },
  });
} catch (err) {
  checkAvailability = false
}

use try catch to handle exceptions.

Check out await reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM