我正在尝试将一个vanilla ES5闭合重写为ES2015 Class。该代码会覆盖window.onerror函数,并充当用于记录目的的全局错误处理程序方法。
我的旧代码看起来像这样。我想知道如何在ES2015中重写它。我如何覆盖Window.onerror?
(function() {
window.onerror = function(errorMessage, url, line) {
try {
if (typeof(url) === "undefined") {
url = "";
}
if (typeof(line) === "undefined") {
line = "";
}
// Avoid error message being too long...
if (errorMessage.length > 300) {
errorMessage = errorMessage.slice(0,300) + "...";
}
errorMessage = errorMessage.replace(/&/g, "%26").replace(/ /g, "+");
url = url;
line = line;
var parentUrl = encodeURIComponent(document.location.href);
// Set error details
var parameters = "error_message=" + errorMessage +
"&url=" + url +
"&line=" + line +
"&parent_url=" + parentUrl;
// Set path to log target
var logUrl = "xxx";
// Set error details as image parameters
new Image().src = logUrl + '?' + parameters;
} catch (e) {}
};
}());
编辑!
现在我正在尝试在JS类中重写它。所以我想我必须扩展Window类或类似的东西(我有Java背景)。但是,据我所知,Window不是一个班级。这就是我到目前为止所拥有的。
所以我需要帮助来覆盖用ES2015编写的window.onerror函数!
export const Logging = new class {
constructor() {
// todo
}
onerror(errorMessage, url, line) {
try {
if (typeof(url) === "undefined") {
url = "";
}
if (typeof(line) === "undefined") {
line = "";
}
// truncate error message if necessary
if (errorMessage.length > 300) {
errorMessage = errorMessage.slice(0,300) + "...";
}
// URI encoding
errorMessage = errorMessage.replace(/&/g, "%26").replace(/ /g, "+");
url = url;
line = line;
var parentUrl = encodeURIComponent(document.location.href);
// set error details
var parameters = "error_message=" + errorMessage +
"&url=" + url +
"&line=" + line +
"&parent_url=" + parentUrl;
// Set path to log target
var logUrl = "xxx";
// set error details as image parameters
var img = new Image().src = logUrl + '?' + parameters;
console.log(img);
}
catch (e) {}
}
}
/* ------------------------------------------------------------------------------------------------------------ */
export default Logging;
答案 0 :(得分:2)
这里唯一有用的是参数默认值。我改变的其他一切都已经在ES5中被误认为了。
window.onerror = function(errorMessage, url="", line="") {
try {
// Avoid error message being too long...
if (errorMessage.length > 303) {
errorMessage = errorMessage.slice(0,300) + "...";
}
var parentUrl = document.location.href;
// Set error details
var parameters = "error_message=" + encodeURIComponent(errorMessage).replace(/%20/g, "+") +
"&url=" + encodeURIComponent(url) +
"&line=" + encodeURIComponent(line) +
"&parent_url=" + encodeURIComponent(parentUrl);
// Set path to log target
var logUrl = "xxx";
// Set error details as image parameters
new Image().src = logUrl + '?' + parameters;
} catch (e) {}
};