Как добавить проверку кода состояния 400 в React - PullRequest
3 голосов
/ 03 августа 2020

Я пытаюсь отредактировать программу, которая требует проверки на наличие ошибки "Неперехваченная (в обещании) Ошибка: запрос не выполнен с кодом состояния 400" создать такие же уникальные данные в таблице. именно поэтому он получает код состояния 400.

Итак, теперь я хочу иметь обработчик ошибок для кода состояния 400 и возвращать строку в текстовом поле с надписью «Duplicate Entry»

Вот мои текущие проверки.

    import * as Yup from "yup";

const InvoiceValidationSchema = Yup.object().shape({
  customer: Yup.object()
    .required("Customer is required."),
  invoiceDate: Yup.string()
    .required("Invoice Date is required"),
  dueDate: Yup.string()
    .required("Due Date is required."),
  invoiceNumber: Yup.string()
    .required("Invoice Number is required"),
  invoiceLines: Yup.array()
    .of(
      Yup.object().shape({
        product: Yup.object().required("Required"),
        quantity: Yup.number().required("Required.").min(1, "Quantity cannot be zero."),
        // price: Yup.number().required("Required.").min(1, "Quantity cannot be zero.").typeError("")
      })
    ).required("Required")
});

export default InvoiceValidationSchema;

Надеюсь, кто-нибудь может мне помочь. Спасибо

Вот и формик

<Formik
    validationSchema={InvoiceValidationSchema}
    initialValues={invoiceCrud}
    onSubmit={(values, action) => {

        const invoiceLines = values.invoiceLines.map(invoiceLine => {
            return {
                ...invoiceLine,
                product: invoiceLine.product,
                price: invoiceLine.price,
                quantity: invoiceLine.quantity,
                totalAmount: invoiceLine.quantity * invoiceLine.price,
                averagePurchasePrice: invoiceLine.product.averagePurchasePrice
            }
        })

        const subTotal = invoiceLines.reduce((sum, line) => {
            return sum + line.totalAmount;
        },0)

        const totalExpense = invoiceLines.reduce((sum, line) => {
            return sum + (line.product.averagePurchasePrice * line.quantity);
        },0)

        const totalAdjustment = 0;
        const netTotal = subTotal - totalAdjustment;

        const totalDueAmount = subTotal - values.subTotal + values.totalDueAmount;


        const invoice ={
            ...values,
            invoiceLines,
            subTotal,
            totalAdjustment,
            netTotal,
            totalExpense,
            totalDueAmount
        }

        if(values.invoiceLines[0].price > 0 && values.invoiceLines[0].quantity > 0){
            submit(invoice);
            setTimeout(() => {
                action.setSubmitting(false);
            }, 1000);
        }else{
            setIsZero(true)
            action.setSubmitting(false)
        }
    }}
    render={
        ({ values, errors, touched, setFieldValue, isSubmitting }) => (
             <Form>
                 <div className="box-body" id="invoice-crud">
                     <div className="row">
                         <div className="col-lg-3 col-md-6 col-sm-12">
                         {errors.invoiceLines ? setIsProductSelected(false) : null}
                         {errors.customer ? setCustomerClass("btn btn-default dropdown-toggle transaction-form__account has-error")
                             : setCustomerClass("btn btn-default dropdown-toggle transaction-form__account")}
                             <DropdownWithSearch
                                 property={
                                     {
                                         title: "Customer",
                                         buttonClass: CustomerClass,
                                         buttonLabel: values.customer ? values.customer.partnerName : "Select Customer",
                                         newButtonLabel: "Customer",
                                         showRemove: values.customer,
                                         modalSelector: "#partner-form"
                                     }
                                 }
                                 option={{
                                     list: partnerDetails.list,
                                     total: partnerDetails.total,
                                     currentPage: partnerDetails.currentPage,
                                     pageSize: partnerDetails.pageSize,
                                     load: changePartnerPage,
                                     display: (element) => element.partnerName,
                                     onClick: (element) => {
                                         setFieldValue("customer", element)
                                     },
                                     removeSelected: () => {
                                         setFieldValue("customer", null)
                                     },
                                     search: (search) => {
                                       dropdownSearch(search, "partner")
                                     }
                                 }}
                             />{errors.customer ? <span className="errorMessage">Please select a customer</span> : null}
                         </div>
                         <FormRow validation={{errors: errors, touched: touched}} field={invoiceNumber}/>
             </Form>
        )}
</Formik>

1 Ответ

0 голосов
/ 03 августа 2020

Вопрос, похоже, связан с Formik и обработкой в ​​нем ошибок бэкэнда, а не чем-либо еще.

Вы можете проверить, как вручную установить бэкэнд-ошибки в formik в этом выпуске github .

И, в частности, , эта песочница , опубликованная пользователем @ t-nunes в github.

Если ваша функция, которая делает запрос, написана в в новом стиле async/await вы, вероятно, будете обрабатывать свои ошибки в блоке try / catch, а для старого стиля .then, .catch вы будете использовать обратный вызов .catch, пока сервер возвращает ошибку код.

...