簡體   English   中英

在 angular 中使用 async/await 時無法捕獲全局異常

[英]Unable to catch global exceptions when using async/await in angular

到目前為止添加代碼片段

app.module.ts

@Injectable()
class UIErrorHandler extends ErrorHandler {
  constructor() {
    super();
  }
  handleError(error) {
    super.handleError(error);
    alert(`Error occurred:${error.message}`);
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AngularFireAuthModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    LoginModule,
    AppRoutingModule,
  ],
  providers: [
    {
      provide: ErrorHandler,
      useClass: UIErrorHandler,
    },
    AuthenticationService,
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
}

LoginComponent -> 在LoginModule中聲明的組件

import { Component } from "@angular/core";
import { Router } from "@angular/router";
import { FormControl, FormGroup, Validators } from "@angular/forms";
import { AuthenticationService } from "~services/authentication.service";

@Component({
  selector: "login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.scss"],
})
export class LoginComponent {
  constructor(public authenticationService: AuthenticationService, public router: Router) {
  }

  signIn = async () => {
    throw new Error("test error")
  };
}

如果從signIn function 中刪除async ,則會捕獲錯誤並且一切正常,但是在async到位的情況下,全局處理程序無法捕獲任何異常。 我如何 go 關於在全球范圍內捕獲基於 promise 的異常?

Uncaught (in promise) Error: test error
at LoginComponent.signIn (login.component.ts:56)
at Object.eval [as handleEvent] (LoginComponent.html:6)
at handleEvent (core.js:43993)
at callWithDebugContext (core.js:45632)
at Object.debugHandleEvent [as handleEvent] (core.js:45247)
at dispatchEvent (core.js:29804)
at core.js:31837
at SafeSubscriber.schedulerFn [as _next] (core.js:35379)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
at SafeSubscriber.next (Subscriber.js:122)

你能在這里檢查一下stackblitz嗎? 這是你調用singIn function的方式嗎?

我基本上做了以下工作:

在組件 ts 中添加代碼

export class AppComponent  {
    constructor() {
    this.signIn();
  }

  signIn = async () => {
    throw new Error('test error');
  }
}

修改module.ts如下:

@Injectable()
class UIErrorHandler extends ErrorHandler {
  constructor() {
    super();
  }
  handleError(error) {
    super.handleError(error);
    alert(`Error occurred:${error.message}`);
  }
}

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ],
    providers: [
    {
      provide: ErrorHandler,
      useClass: UIErrorHandler,
    }
  ],
})
export class AppModule { }

如您所見,這本身就可以工作。 檢查您的 angular 版本,因為過去存在未等待承諾的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM