方法一:react16以后的版本增加異常捕獲
componentDidCatch(error, info) { const isNewError = (error.toString() !== this.state.prevError.toString());// should only run once if (isNewError) {//判斷兩次錯誤不一致才再次執行,不然一直循環 this.logErrorToMyService(error, info); this.setState({ prevError: error }); } }
方法二:使用window.onerror全局捕獲異常
window.onerror = function (errorMessage, scriptURI, lineNo, columnNo, error) { console.log('errorMessage: ' + errorMessage); // 異常信息 console.log('scriptURI: ' + scriptURI); // 異常文件路徑 console.log('lineNo: ' + lineNo); // 異常行號 console.log('columnNo: ' + columnNo); // 異常列號 console.log('error: ' + error); // 異常堆棧信息 };
方法三:使用try catch捕獲
在每個方法內進行捕獲,對所有的字段進行校驗
let optionfloor = null; try { optionfloor = ( floorList ? floorList.map((item) => { return <Option key={item.id} value={item.id}>{item.name}</Option> }) : null ) } catch (e) { optionfloor = null; }
總結:項目內進行的異常判斷少之又少,這是很危險的行為,每次接口出現的數據不符合預期都會出現空白頁崩的現象。在未來的項目內,異常判斷也要加入規范內,是項目很重要的一個組成部分,最起碼的全局有異常捕獲,其次每個具體的頁面內判斷字段是否存在,類型是否正確。