Search code examples
javascriptangulartypescriptsubscription

How to generaet error in httpClient call in Angular?


I have the following method in for a search feature in my Angular app, and I want to test the error part. However, it does not hit error block. Is it related to subscribe? Or what should I use for this method or approach?

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

Solution

  • As I understand, you want to throw exception at line 'res = undefined; //test: added to create error'. Use try catch for this purpose. The (err) block is used for http errors. For example, in C# type this in your action result:

       [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();
        }
    

    Pay attention the line: return BadRequest("unauthorized access");