如何在 Angular 中的 httpClient 调用中生成错误?

我的 Angular 应用程序中有以下搜索功能的方法,我想测试错误部分。但是,它不会命中错误块。和订阅有关系吗?或者我应该使用什么方法或途径?


this.searchGetCall(text).subscribe((res) => {

    res = undefined; //test: added to create error

    console.log('res', res.constructor());

    this.isSearching = false;

    this.apiResponse = res;

  }, (err) => {

    debugger; //cannot hit this block

    this.isSearching = false;

    console.log('error', err);

  });




searchGetCall(term: string) {

  if (term === '') {

    return of([]);

  }

  return this.httpClient.get('http://www.omdbapi.com/?s=' + term + '&apikey=' + APIKEY, { params: PARAMS.set('search', term) });

}


潇湘沐
浏览 134回答 3
3回答

郎朗坤

据我了解,您想在 'res = undefined; 行抛出异常;//测试:添加以创建错误'。为此目的使用 try catch。(err) 块用于处理 http 错误。例如,在 C# 中,在操作结果中键入以下内容:&nbsp; &nbsp;[HttpGet("Get/{id}")]&nbsp; &nbsp; public async Task<ActionResult<UserDto>> Get(long id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ServiceResult<IEnumerable<UserBo>> result = await serviceManager.User_Service.FindAsync(filterCriteria);&nbsp; &nbsp; &nbsp; &nbsp; if (result.Success)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userBo = result.Data.FirstOrDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (userBo == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return NotFound();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ServiceResult<bool> resultAutorized = await GetAutorizedUserStatusById(userBo);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!resultAutorized.Success || !resultAutorized.Data)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return BadRequest("unauthorized access");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UserDto userDto = UserBo.ConvertToDto(userBo);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return userDto;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return BadRequest(result.Error);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.FirstOrDefaultAsync();&nbsp; &nbsp; }注意这一行: return BadRequest("未经授权的访问");

HUH函数

这不像try/catch。订阅错误块的到达取决于 HTTP 代码状态(403,404,500 等),而不是脚本执行错误。您的测试只是使脚本崩溃,而不是模拟 HTTP 错误代码。

慕尼黑5688855

我假设您的 searchGetCall 是一个网络请求,并且它返回一个可观察值。当您的 Web 请求返回 http 状态代码错误时,您的错误块将被执行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript