使用闪电数据 table 对多条记录进行内联编辑。从 LWC 中的 then 方法中的验证规则中获取 Uncaught (in promise)

Using lightning data table with inline editing for multiple records. Getting getting Uncaught (in promise) from validation rule in then method in LWC

我有一个 Lightning Data table,我正在使用 Promise.all(promises),如文档中所述,在内联编辑中更新多个记录更改。 https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.data_table_inline_edit

我有一个验证规则,当我尝试更新其中一个字段中的负值记录时会抛出错误,该字段在内联编辑中用作列。问题是我得到了未捕获的(承诺的)并且我也可以在开发人员控制台上看到验证规则错误消息,但其中包含从验证规则抛出的消息。

错误 - {status: 400, body: {...}, headers: {...}} body: enhancedErrorType: “RecordError” 消息:“尝试更新记录时发生错误。请重试。”输出:{errors: Array(1), fieldErrors: {...}} statusCode: 400 [[Prototype]]: Object headers: {} status: 400 ok: (...) statusText: (...) [[Prototype ]]: 对象。

代码-

handleSave(event) {
        //save last saved copy
        this.lastSavedData = JSON.parse(JSON.stringify(this.tableData));
        //this.tableData = this.lastSavedData;
        console.log('this.tableData', JSON.stringify(this.tableData));
        const recordInputs =  this.draftValues.slice().map(draft => {
            const fields = Object.assign({}, draft);
            return { fields };
        });
        console.log('recordInputs:', recordInputs);
        const promises = recordInputs.map(recordInput => {
            updateRecord(recordInput);
        });
        Promise.all(promises).then((rec) => {
            console.log('::inside then'+ rec);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Records updated',
                    variant: 'success'
                })
            );
            //Clear all draft values
            this.draftValues = [];
            refreshApex(this.data);

            console.log('Refreshed Data', JSON.stringify(refreshApex(this.data)));
            //location.reload();
            //return refreshApex(this.data);
            return refreshApex(this.data);
            // Display fresh data in the datatable
            
        }).catch(error => {
            console.log('error',JSON.stringify(error));
            this.dispatchEvent(
                new ShowToastEvent({
                  title: "Error on update",
                  message: error.body.output.errors[0].errorCode + '- '+ error.body.output.errors[0].message,
                  variant: "error"
                })
              );
        });
    }

期望使用 catch 块中的错误对象显示消息,但即使在未捕获的异常之后执行也不会覆盖 catch 块。

任何建议都可能有帮助。

如果我的回答没有涵盖您的问题,我提前道歉。另外,这很难,因为我没有你组件的其余文件。

我创建了一个与您创建的组件非常相似的组件(我重复使用了您的大部分代码)。我正在使用一些硬编码的联系人。我在系统中创建了一个验证规则,以防止在 Age__c 为 <= 0.

时保存联系人

通过以下代码,我已经实现了我所理解的您所需要的:

HTML:

<template>
  <lightning-card title="Datatable Example" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <template if:true={records}>
        <lightning-datatable
          key-field="Id"
          data={records}
          columns={columns}
          onsave={handleSave}
        >
        </lightning-datatable>
      </template>
    </div>
  </lightning-card>
</template>

JS:

import { LightningElement } from "lwc";
import { updateRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { refreshApex } from "@salesforce/apex";

export default class TableEdit extends LightningElement {
  columns = [
    { label: "Id", fieldName: "Id" },
    { label: "Age", fieldName: "Age__c", editable: true }
  ];
  records = [
    { Id: "0033O00000gEXlNQAW", Age__c: 10 },
    { Id: "0033O00000gEXlIQAW", Age__c: 15 }
  ];

  handleSave(event) {
    //save last saved copy
    const recordInputs = event.detail.draftValues.slice().map((draft) => {
      const fields = Object.assign({}, draft);
      return { fields };
    });
    console.log("recordInputs:", recordInputs);
    const promises = recordInputs.map((recordInput) => {
      return updateRecord(recordInput);
    });
    Promise.all(promises)
      .then((rec) => {
        console.log("::inside then" + rec);
        this.dispatchEvent(
          new ShowToastEvent({
            title: "Success",
            message: "Records updated",
            variant: "success"
          })
        );
        //Clear all draft values
        this.draftValues = [];
        refreshApex(this.data);

        console.log("Refreshed Data", JSON.stringify(refreshApex(this.data)));
        //location.reload();
        //return refreshApex(this.data);
        return refreshApex(this.data);
        // Display fresh data in the datatable
      })
      .catch((error) => {
        console.log("error", JSON.stringify(error));
        this.dispatchEvent(
          new ShowToastEvent({
            title: "Error on update",
            message:
              error.body.output.errors[0].errorCode +
              "- " +
              error.body.output.errors[0].message,
            variant: "error"
          })
        );
      });
  }
}

我在您共享的代码中注意到的一件重要事情是以下部分:

const promises = recordInputs.map(recordInput => {
    updateRecord(recordInput);
});

由于箭头函数符号的工作原理,如果包含花括号,则需要在 updateRecord() 调用前添加 return 关键字。这是因为 return 关键字仅在您使用不带大括号的“单行函数”时才被隐式考虑。不确定这是否是问题所在。