gpt4 book ai didi

javascript - 从 Chrome 扩展内容脚本中抛出调试

转载 作者:行者123 更新时间:2023-11-28 08:42:55 27 4
gpt4 key购买 nike

简短版本

尝试编写一个返回调用堆栈(减去当前位置)的调试命令。我想我会用:

try {
throw new Error(options["msg"])
} catch (e) {
e.stack.shift;
throw (e);
}

但我不知 Prop 体该怎么做。显然我不能像这样e.stack.shift。而且这总是导致未捕获错误——但这些应该只是调试消息。

长版

我决定我的内容脚本需要一个调试库。这是:

调试.js

var debugKeys = {
"level": ["off", "event", "function", "timeouts"],
"detail": ["minimal", "detailed"]
};
var debugState = { "level": "off", "detail": "minimal" };

function debug(options) {
if ("level" in options) {
if (verifyDebugValue("level", options["level"]) == false)
return
}
if ("detail" in options) {
if (verifyDebugValue("detail", options["detail"]) == false)
return
}

console.log(options["msg"]);
}

function verifyDebugValue(lval, rval){
var state = 10; // sufficiently high
for (k in debugKeys[lval]) {
if (debugKeys[lval][k] == rval) {
return true;
}
if (debugKeys[lval][k] == debugState[lval]) { // rval was greater than debug key
return false;
}
}
}

使用时,您可以更改代码中的debugState以满足您的需要。它仍在进行中,但效果很好。

要从另一个内容脚本使用它,只需将其加载到 list 中,例如:

manifest.json

  "content_scripts": [
{
"js": ["debug.js", "foobar.js"],
}
],

然后这样调用它:

debug({"level": "timeouts", "msg": "foobar.js waitOnElement() timeout"});

生成:

foobar.js waitOnElement() timeout debug.js:17

这就是我的问题。目前,它使用控制台日志,因此所有调试语句都来自同一 debug.js 行。我宁愿返回调用上下文。我想我需要这样的东西:

try {
throw new Error(options["msg"])
} catch (e) {
e.stack.shift;
throw (e);
}

但我不知 Prop 体该怎么做。显然我不能像这样e.stack.shift。而且这总是导致未捕获错误——但这些应该只是调试消息。

最佳答案

您无法避免提及 debug.js 中的这一行,因为使用 throw (...)console.log/error( ...) 您的 debug.js 将发出该命令。

您可以做的是在代码中添加一些 try-catch block ,然后在 catch block 中将错误对象传递给您的调试函数,该函数将根据其 处理它调试状态

无论如何,目前还不清楚您如何使用调试库(以及为什么需要从堆栈跟踪中删除最后一个调用,但您可以尝试这样的操作:

  1. 将堆栈跟踪(实际上是多行字符串)拆分为多行。
  2. 隔离不属于错误消息的第一行(对应于最后一次调用)。
  3. 将新的堆栈跟踪与删除的行放在一起。

例如:

function removeLastFromStack(stack, errMsg) {
var firstLines = 'Error: ' + errMsg + '\n';
var restOfStack = stack
.substring(firstLines.length) // <-- skip the error's message
.split('\n') // <-- split into lines
.slice(1) // <-- "slice out" the first line
.join('\n'); // <-- put the rest back together
return firstLines + restOfStack;
}

function myDebug(err) {
/* Based on my `debugState` I should decide what to do with this error.
* E.g. I could ignore it, or print the message only,
* or print the full stack-trace, or alert the user, or whatever */
var oldStack = err.stack;
var newStack = removeLastFromStack(oldStack, err.message);
console.log(newStack);
//or: console.error(newStack);
}

/* Somewhere in your code */
function someFuncThatMayThrowAnErr(errMsg) {
throw new Error(errMsg);
}

try {
someFuncThatMayThrowAnErr('test');
} catch (err) {
myDebug(err);
}

...但我仍然不明白从跟踪中删除最后一个调用有何帮助

关于javascript - 从 Chrome 扩展内容脚本中抛出调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290565/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com