Last active
March 1, 2020 15:22
-
-
Save atskimura/9645b32496f183618d8970ce374e57dc to your computer and use it in GitHub Desktop.
LWCのApexエラー処理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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の取得に失敗しました。'); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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