在订阅中捕获 Angular 17 转换为字符串时出错

问题描述 投票:0回答:1

我无法发现错误。

它正确地捕获了拦截器中的错误。

拦截器捕获错误

{
    "headers": {
        "normalizedNames": {},
        "lazyUpdate": null
    },
    "status": 409,
    "statusText": "Conflict",
    "url": "myurl.com/url",
    "ok": false,
    "name": "HttpErrorResponse",
    "message": "Http failure response for myurl.com/url: 409 Conflict",
    "error": {
        "status": 409,
        "message": "Email already exists"
    }
}

但是在订阅中,错误将此值作为字符串:

Unknown error [object Object]

拦截器

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError(e => {
      return throwError(() => e);
    })
  );
};

服务

@Injectable({
  providedIn: 'root',
})
export class UserService {
  private readonly _http = inject(HttpClient);

  exists$(email: string): Observable<UserExistsResponse> {
    return this._http.post<UserExistsResponse>(myurl.com/url, {
      email,
    });
  }
}

组件

 this._userService
      .exists$(this.accountFormGroup.controls.email.value)
      .subscribe({
        next: res => {
          // Do some stuff
        },
        error: e => {
          console.log(e); // Prints : Unknown error [object Object]
          this.setError(e);
        },
      });

app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(APP_ROUTES, withViewTransitions(), withPreloading(PreloadAllModules)),
    provideHttpClient(
      withXsrfConfiguration(environment.xsrf),
      withInterceptors([authenticationInterceptor, errorInterceptor])
    ),
    provideAnimationsAsync('animations'),
  ],
};
angular rxjs
1个回答
0
投票

你试图在你的拦截器中返回 return throwError(() => e);,它实际上会返回一个 Observable 你可以阅读 ThrowError RxJs

的官方文档

解决方案是直接抛出错误,而不使用 throwError for ex:

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError(e => {
      throw e;
    })
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.