Bir hata mesajı [duplicate] üreterek console.error () gibi izleme alın

Dec 13 2020

Bunu yaptığımda console.error('Custom Error')nereden geldiğine dair güzel bir iz buluyorum

Örneğin:

func1();

function func1() {
  func2();
}

function func2() {
  func3();
}

function func3() {
  console.error('Custom Error');
}

Alırım:

Bunu bir hata oluşturmadan nasıl yapabilirim, daha çok console.log()?

Yanıtlar

Danziger Dec 13 2020 at 06:44

Bunun console.trace()yerine kullanabilirsiniz console.error().

Konsolda gördüğünüz şey şudur console.trace():

Trace
func3 @ js:24
func2 @ js:19
func1 @ js:15
(anonymous) @ js:12

Ve bununla 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

Yığın izini yalnızca günlüğe kaydetmek yerine bir değişkene almak istiyorsanız, Error.captureStackTrace(targetObject)veya kullanabilirsiniz Error().stack, ancak her ikisi de standart değildir:

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;
}