' P '

whatever I will forget

LWC サーバーエラーの処理

Lightning Web コンポーネントのサーバーエラー処理

  • LDS ワイヤーアダプター、LDS 関数、Apex コールで発生するエラーには特定の構造がある
  • エラーに関する情報を取得するには、JavaScript コードでエラー応答を処理する

@wireでリンクしたプロパティの場合

import { LightningElement, api, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import getRelatedContacts from '@salesforce/apex/AccountController.getRelatedContacts';
export default class WireApexProperty extends LightningElement {
    @api recordId;
    @wire(getRelatedContacts, { accountId: '$recordId' })
    contacts;
    get errors() {
        return (this.contacts.error) ?
            reduceErrors(this.contacts.error) : [];
    }
}
  • ldsUtils (LWCサンプルアプリ) からインポートしたreduceErrors関数で発生した全てのエラーメッセージの配列を返却できる

@wireでリンクした関数の場合

import { LightningElement, api, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import getRelatedContacts from '@salesforce/apex/AccountController.getRelatedContacts';
export default class WireApexFunction extends LightningElement {
    @api recordId;
    errors;
    @wire(getRelatedContacts, { accountId: '$recordId' })
    wiredContacts({data, error}) {
        if (error)
            this.errors = reduceErrors(error);
    }
}

命令的に関数をコールする場合のエラー処理

import { LightningElement, api, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import getRelatedContacts from '@salesforce/apex/AccountController.getRelatedContacts';
export default class CallApexImperative extends LightningElement {
    @api recordId;
    errors;
    handleButtonClick() {
        getRelatedContacts({
            accountId: this.recordId
        })
            .then(contacts => {
                // code to execute if the promise is resolved
            })
            .catch(error => {
                this.errors = reduceErrors(error); // code to execute if the promise is rejected
            });
    }
}