gue*_*tli 6 javascript json sentry typescript
我想学习TypeScript.
我有一个由iftry方法event_from_exception()(Python)返回的JSON字典.
我想将它格式化为带有可扩展局部变量和pre_和post_context的漂亮HTML.结果应该大致如下:
这是json的一个例子:
{
"exception": {
"values": [
{
"stacktrace": {
"frames": [
{
"function": "main",
"abs_path": "/home/modlink_cok_d/src/sentry-json.py",
"pre_context": [
"from sentry_sdk.utils import event_from_exception",
"",
"def main():",
" local_var = 1",
" try:"
],
"lineno": 9,
"vars": {
"exc": "ValueError()",
"local_var": "1"
},
"context_line": " raise ValueError()",
"post_context": [
" except Exception as exc:",
" event, info = event_from_exception(sys.exc_info(), with_locals=True)",
" print(json.dumps(event, indent=2))",
"",
"main()"
],
"module": "__main__",
"filename": "sentry-json.py"
}
]
},
"type": "ValueError",
"value": "",
"module": "exceptions",
"mechanism": null
}
]
},
"level": "error"
}
Run Code Online (Sandbox Code Playgroud)
怎么能用TypeScript完成?
要在没有框架的情况下自己完成此操作,我将为 json 中的每个元素创建一个类。然后我会toHTML(domParent)在每个类上都有一个方法来迭代它的子组件:
class Stacktrace {
frames: Frame[];
type: string;
value: string;
module: string;
mechanism: string;
toHTML(domParent) {
for (let frame of Frame) {
frame.toHTML(domParent);
}
domParent.addChild(`<div>${type}</div>`);
domParent.addChild(`<div>${value}</div>`);
domParent.addChild(`<div>${module}</div>`);
domParent.addChild(`<div>${mechanism}</div>`);
}
}
Run Code Online (Sandbox Code Playgroud)
这只是伪代码,但应该能让你走上正轨。
你可以使用https://app.quicktype.io给你。
export interface Welcome {
exception: Exception;
level: string;
}
export interface Exception {
values: Value[];
}
export interface Value {
stacktrace: Stacktrace;
type: string;
value: string;
module: string;
mechanism: null;
}
export interface Stacktrace {
frames: Frame[];
}
export interface Frame {
function: string;
abs_path: string;
pre_context: string[];
lineno: number;
vars: Vars;
context_line: string;
post_context: string[];
module: string;
filename: string;
}
export interface Vars {
exc: string;
local_var: string;
}
Run Code Online (Sandbox Code Playgroud)
data.如果您没有更喜欢的 Web 框架(React、Vue),则可以使用模板文字。
const data = JSON.parse(json);
const html = `
<div>${data.exception.values.map(value => `
<div>${value.stacktrace.frames.map(frame => `
<div>
<pre>${frame.abs_path} in ${frame.function}</pre>
<div style="margin-left:2rem">
${frame.pre_context.map((line, i) =>`
<pre>${frame.lineno + i - frame.pre_context.length}. ${line}</pre>
`).join("")}
<pre><strong>${frame.lineno}. ${frame.context_line}</strong></pre>
${frame.post_context.map((line, i) => `
<pre>${frame.lineno + i + 1}. ${line}</pre>
`).join("")}
</div>
</div>
`).join("")}</div>
`).join("")}</div>
`;
document.body.innerHTML = html;
Run Code Online (Sandbox Code Playgroud)
例如:https : //codesandbox.io/s/52x8r17zo4
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |