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

How to generaet error in httpClient call in Angular?

我的 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) });
}

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

据我了解,您想在第 'res = undefined; //test: added to create error' 行抛出异常。为此使用 try catch。 (err) 块用于 http 错误。 例如,在 C# 中,在您的操作结果中键入:

   [HttpGet("Get/{id}")]
    public async Task<ActionResult<UserDto>> Get(long id)
    {            
        ServiceResult<IEnumerable<UserBo>> result = await serviceManager.User_Service.FindAsync(filterCriteria);
        if (result.Success)
        {
            userBo = result.Data.FirstOrDefault();
            if (userBo == null)
                return NotFound();
            else
            {
                ServiceResult<bool> resultAutorized = await GetAutorizedUserStatusById(userBo);
                if (!resultAutorized.Success || !resultAutorized.Data)
                    return BadRequest("unauthorized access");
            }

            UserDto userDto = UserBo.ConvertToDto(userBo);

            return userDto;
        }
        else
        {
            return BadRequest(result.Error);
        }
                           .FirstOrDefaultAsync();
    }

注意这行: return BadRequest("未授权访问");

我假设您的 searchGetCall 是一个 Web 请求并且它 returns 是一个可观察的。当您的网络请求 returns 一个 http 状态代码错误时,您的错误块将被执行。