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 => {
})
.catch(error => {
this.errors = reduceErrors(error);
});
}
}