3 回答
TA貢獻1808條經驗 獲得超4個贊
這種方法不依賴于任何 JS 框架。這是香草javascript。
我從你的問題中可以理解的是,你想訪問error拋給的未捕獲消息console,你還提到你正在處理一些錯誤報告功能。有時您可能還需要捕獲console.log/warn/info您可以覆蓋如下所示的行為以捕獲錯誤/消息,因為控制臺由瀏覽器處理。因此,實現該行為的唯一方法是覆蓋。
附上一個片段,讓您了解捕獲瀏覽器控制臺數據和處理錯誤
// Add this file to app.component maybe
let logStatements = [];
(() => {
window.addEventListener("error", ev => {
reportError(ev);
})
// Capturing console logs
var oldLog = console.log;
console.log = function (message) {
oldLog.apply(console, arguments);
logStatements.push({
type: "console.log",
data: message,
});
};
})(logStatements);
console.log('hello');
console.log('world');
// Array of captured console.logs
console.info(logStatements)
// Here you can send this to any backend or something
function reportError(ev) {
console.log(`${ev.message} was caught in ${ev.filename}`);
}
// logging 'user' variable which is not defined to check if it gets caught
console.log(user);
TA貢獻1827條經驗 獲得超8個贊
如果您不依賴控制臺,這是一種更好的方法。這取決于您,但我認為讓錯誤到達控制臺并不是最佳做法。無論如何,您可以在錯誤到達控制臺之前捕獲錯誤。
對于 HTTPClient 錯誤,可以使用錯誤 Iterceptor
對于 Angular“代碼”錯誤,我建議使用全局錯誤處理程序
TA貢獻1725條經驗 獲得超8個贊
這是我從不同來源匯總的解決方案。它捕獲控制臺中顯示的大多數內容(有些無法捕獲)。
它使它可以作為console.everything一個數組使用,其中包含類型、時間戳和發送到控制臺的數據。
最好將它包含在標頭中作為其自己<script>標記中的第一個腳本,以確保它先于其他任何內容運行并且不受稍后運行的代碼的影響。
if (console.everything === undefined) {
console.everything = [];
function TS(){
return (new Date).toLocaleString("sv", { timeZone: 'UTC' }) + "Z"
}
window.onerror = function (error, url, line) {
console.everything.push({
type: "exception",
timeStamp: TS(),
value: { error, url, line }
})
return false;
}
window.onunhandledrejection = function (e) {
console.everything.push({
type: "promiseRejection",
timeStamp: TS(),
value: e.reason
})
}
function hookLogType(logType) {
const original= console[logType].bind(console)
return function(){
console.everything.push({
type: logType,
timeStamp: TS(),
value: Array.from(arguments)
})
original.apply(console, arguments)
}
}
['log', 'error', 'warn', 'debug'].forEach(logType=>{
console[logType] = hookLogType(logType)
})
}
添加回答
舉報
