如何手动抛出可观察错误



我正在做一个Angular应用,在这个应用中,我通过HTTP做了一个rest调用,如下所示:

login(email, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({ headers: headers });
    let body = `identity=${email}&password=${password}`;
    return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
    .map((res: any) => {
        let response: any = JSON.parse(res._body);
        if (response.success == 0) {
          Observable.throw(response);  // not working
        } else if (response.success == 1) {
          console.log('success');
          localStorage.setItem('auth_token', 'authenticated');
          this.loggedIn = true;
          return response;
        }
    });
}

基本上我希望我的组件得到响应&订阅调用错误,即

this._authenticateService.login(this.loginObj['identity'],this.loginObj['password']).subscribe(
  (success)=>{      
    this.credentialsError=null;  
    this.loginObj={};  
    this._router.navigate(['dashboard']);    
  },
  (error)=>{
    console.log(error);        
    this.credentialsError=error;     
  }
);

但是我的API总是返回成功,因为它是这样定义的。

如果response.success == 0,我如何抛出错误消息,以便它将在订阅回调的错误参数内访问?

if (response.success == 0) {
   throw Observable.throw(response);  
 } 

编辑rxjs 6:

if (response.success == 0) {
   throw throwError(response);  
 } 

rxjs 6

import { throwError } from 'rxjs';
if (response.success == 0) {
  return throwError(response);  
}

rxjs 5

import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
if (response.success == 0) {
  return new ErrorObservable(response);  
}

使用ErrorObservable返回的内容由您决定

使用RXJS 6

import { throwError } from 'rxjs';
throwError('hello');

rxjs 5

throw response;

throw Observable.throw(response);

rxjs 7

throwError(() => new Error(response))

更多信息https://rxjs.dev/deprecations/breaking-changes throwerror

下面是官方示例(发出数字7,然后错误'oops!'):

import { throwError, concat, of } from 'rxjs';
const result = concat(of(7), throwError(new Error('oops!')));
result.subscribe(x => console.log(x), e => console.error(e));

:https://rxjs-dev.firebaseapp.com/api/index/function/throwError

使用catch操作符

this.calcSub = this.http.post(this.constants.userUrl + "UpdateCalculation", body, { headers: headers })
   .map((response: Response) => {
      var result = <DataResponseObject>response.json();
         return result;
   })
   .catch(this.handleError)
   .subscribe(
      dro => this.dro = dro,
      () => this.completeAddCalculation()
   );

并像这样处理错误:

private handleError(error: Response) {
    console.error(error); // log to console instead
    return Observable.throw(error.json().error || 'Server Error');
}

我的大多数问题都与导入有关,所以这里是为我工作的代码…

import {_throw} from 'rxjs/observable/throw';
login(email, password) {
...
    return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
    .map((res: any) => {
...
        if (response.success == 0) {
           _throw(response);  
        } else if (response.success == 1) {
...
        }
    });
}

这将是解决方案,如果你面临的错误,如…

错误TypeError: WEBPACK_IMPORTED_MODULE_2_rxjs_Observable .Observable。Throw不是函数

通常当您抛出错误时,您将在问题发生的确切时刻这样做,并且您希望立即引发它,但情况可能并不总是如此。

例如,有timeoutWith()操作符,这可能是您需要这样做的最有可能的原因之一。

results$ = server.getResults().pipe(timeoutWith(10000, ....) )

接受一个'error factory',它是一个函数。

 errorFactory = () => 'Your error occurred at exactly ' + new Date()

results$ = server.searchCustomers(searchCriteria).pipe(timeoutWith(10000, 
              () => 'Sorry took too long for search ' + JSON.stringify(searchCriteria)) )

请注意,当使用timeoutWith时,您将永远无法获得实际的服务器响应-因此,如果服务器给出特定的错误,您将永远不会看到它。上面的示例在调试中非常有用,但是如果使用上面的示例,请确保不要将错误显示给最终用户。

错误工厂是有用的,因为它在实际错误发生之前不会评估代码。因此,你可以把'昂贵'或调试操作放在里面,这些操作将在最终需要错误时执行。

如果你需要在超时时间以外的地方使用'factory'来创建错误,你可以使用以下命令:

 EMPTY.pipe(throwIfEmpty(errorFactory)) 

可以使用catchError(error) =>Console.log(错误)在管道

最新更新