角度/打字稿-错误对象未返回完整的堆栈信息

时间:2019-09-11 19:23:08

标签: javascript angular typescript stack

我正在尝试编写一个异常处理程序,该处理程序将在遇到错误时记录堆栈跟踪。错误对象无法正确返回堆栈。以下片段演示了该问题:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-error-stack';

  runTest() {
    try {
      let invalidJson = 'invalid json'; 
      let someObject = JSON.parse(invalidJson); 
    }
    catch(error) {
      console.log('----- error and error.stack are not the same! -----'); 
      console.log('------------------------------------------');
      console.log('Stack: ', error.stack); 
      console.log('------------------------------------------');
      console.log('Error', error); 
      console.log('------------------------------------------');
    }
  }
}

当我运行上面的命令时,我得到了不同的结果。 console.log(error.stack)不包含与console.log(error)相同的信息。

console.log(error.stack)显示发生在以下位置的错误:

AppComponent.runTest (http://localhost:4220/main.js:102:35)

console.log(error)显示发生在以下位置的错误:

AppComponent.runTest (app.component.ts:14)

如何获取正确的堆栈跟踪?

上面的代码段产生以下输出:

  

堆栈:SyntaxError:JSON中位置0处的意外令牌i       在JSON.parse()       在AppComponent.runTest(http://localhost:4220/main.js:102:35)       在Object.eval [作为handleEvent](ng:///AppModule/AppComponent.ngfactory.js:15:27)       在handleEvent(http://localhost:4220/vendor.js:74619:122)       在callWithDebugContext(http://localhost:4220/vendor.js:76238:27)       在Object.debugHandleEvent [作为handleEvent](http://localhost:4220/vendor.js:75873:12)       在dispatchEvent(http://localhost:4220/vendor.js:61706:25)       在http://localhost:4220/vendor.js:73551:16       在HTMLButtonElement。 (http://localhost:4220/vendor.js:79297:38)       在ZoneDelegate.invokeTask(http://localhost:4220/polyfills.js:3397:31

     

错误:SyntaxError:JSON中位置0处的意外令牌i       在JSON.parse()       在AppComponent.runTest(app.component.ts:14)       在Object.eval [作为handleEvent](AppComponent.html:3)       在handleEvent(core.js:43992)       在callWithDebugContext(core.js:45631)       在Object.debugHandleEvent [作为handleEvent](core.js:45246)       在dispatchEvent(core.js:29803)       在core.js:42924       在HTMLButtonElement。 (platform-b​​rowser.js:2668)       在ZoneDelegate.invokeTask(zone-evergreen.js:391)

0 个答案:

没有答案
相关问题