Skip to content

Instantly share code, notes, and snippets.

@atskimura
Last active March 1, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atskimura/9645b32496f183618d8970ce374e57dc to your computer and use it in GitHub Desktop.
Save atskimura/9645b32496f183618d8970ce374e57dc to your computer and use it in GitHub Desktop.
LWCのApexエラー処理
import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/NotifyApexErrorSampleController.getContacts'
import { notifyApexError } from 'c/util';
export default class NotifyApexErrorSample extends LightningElement {
@track contacts;
@wire(getContacts)
wiredContacts({ error, data }) {
if (data) {
this.contacts = data;
} else if (error) {
notifyApexError(this, error, 'Contact取得失敗', 'Contactの取得に失敗しました。');
}
}
}
import { ShowToastEvent } from 'lightning/platformShowToastEvent'
/**
* 以下のように呼び出す。
* <pre>
* notifyApexError(this, error, '保存に失敗', '保存に失敗しました。');
* </pre>
*
* @param {*} cmp LightningElement自身
* @param {*} error Apexが例外を投げたときのエラーオブジェクト
* @param {*} title Toastのタイトル
* @param {*} defaultMessage エラーメッセージが取得できないときToastの本文に表示するメッセージ
*/
const notifyApexError = (cmp, error, title, defaultMessage) => {
let errorMessage;
if (error instanceof Error) {
errorMessage = error.stack || `${error.name}: ${error.message}`;
window.console.error(error);
} else {
if (error && error.body) {
const {'body': {exceptionType, message, stackTrace}} = error;
errorMessage = [exceptionType, message, stackTrace].filter(v=>{return v}).join(', ');
}
try {
window.console.error(JSON.parse(JSON.stringify(error)));
} catch(e) {
window.console.error(error);
}
}
const event = new ShowToastEvent({
title: title,
message: errorMessage || defaultMessage,
variant: 'error'
});
cmp.dispatchEvent(event);
};
export { notifyApexError };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment