Holen Sie sich Trace wie console.error () mit einer Fehlermeldung [Duplikat]
Dec 13 2020
Wenn ich das tue, console.error('Custom Error')
bekomme ich eine schöne Spur davon, woher es kam
Beispielsweise:
func1();
function func1() {
func2();
}
function func2() {
func3();
}
function func3() {
console.error('Custom Error');
}
Ich bekomme:

Wie kann ich das tun, ohne einen Fehler zu erzeugen console.log()
?
Antworten
Danziger Dec 13 2020 at 06:44
Sie könnten console.trace()anstelle von verwenden console.error().
Folgendes sehen Sie auf der Konsole mit console.trace()
:
Trace
func3 @ js:24
func2 @ js:19
func1 @ js:15
(anonymous) @ js:12
Und das mit console.error()
:
Custom Error
console.error @ snippet-javascript-console.min.js?v=1:1
func3 @ js:23
func2 @ js:19
func1 @ js:15
(anonymous) @ js:12
Wenn Sie den Stack-Trace in eine Variable umwandeln möchten, anstatt ihn nur zu protokollieren, können Sie Error.captureStackTrace(targetObject)oder verwenden Error().stack, aber beide sind nicht Standard:
func1();
function func1() {
func2();
}
function func2() {
func3();
}
function func3() {
const fakeErrorObject = {};
Error.captureStackTrace(fakeErrorObject)
const captureStackTraceTrace = fakeErrorObject.stack;
const errorStackTrace = Error('Foo').stack;
console.log(captureStackTraceTrace.replaceAll('at', '👉'));
console.log(errorStackTrace.replaceAll('at', '👉'));
}
.as-console-wrapper {
max-height: none !important;
}