typescript 403错误未被捕获错误函数Angular 7

cwtwac6a  于 2023-02-10  发布在  TypeScript
关注(0)|答案(2)|浏览(135)

我写了下面的代码,当我在浏览器中运行代码时,登录API给出了403响应代码。但是我不能捕捉到这个错误并在控制台记录下来。谁能告诉我我的代码有什么问题吗?

this.http

    .post("login", {

      username,
      password
    }).pipe(
      catchError(err => {
        console.log('Handling error locally and rethrowing it...', err);
        return throwError(err);
      })
    )
    .subscribe(
      (response: any) => {
       }
       error=> {

        console.log(error);

       }
    )
tkclm6bt

tkclm6bt1#

试试下面这样的:

let params = {
          "login_id" : id,
          "password" : pass
        };

    this.http.post(loginUrl, params, {observe:'response'}).subscribe((data:any) => {
        console.log('http login -> ', data);
      }, (err : HttpErrorResponse) => {
        console.log('http login error -> ', err);
      });
    }

或者试试这个:

this.http.post("login", {
      username,
      password
    })
    .pipe(catchError(this.errorMgmt))
    .subscribe(
      (response: any) => {
        console.log('res',response)
       }
    )

  errorMgmt(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
      console.log('err',errorMessage);
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${JSON.stringify(error.error)}`;
      console.log('err',errorMessage);
    }
    console.log('errorMgmt -> ',(errorMessage));
    return throwError(errorMessage);
  }
eimct9ow

eimct9ow2#

如果您在拦截器中捕获到错误,就会发生这种情况。

因此,如果您已经实现了一个如下所示的拦截器,您可以控制台记录错误,如下所示:

private handleAuthError(err: HttpErrorResponse): Observable<any> {
    if (err.status === 401 || err.status === 403) {
        this.router.navigateByUrl(`/login`);
        this.authService.isLoggedIn$.next(false)
        console.log("HERE YOU CAN CONSOLE LOG THE ERROR")
        return of(err.message); 
    }
    return throwError(err);
  }
  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const req = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.cookieService.get('token')}`
      }
    })
    return next.handle(req).pipe(catchError(x=> this.handleAuthError(x)));

相关问题