Home > OS >  Handling .NET api response in Angular using NgRx
Handling .NET api response in Angular using NgRx

Time:12-20

With following code i'm dispatching an action to login a user. Whenever bad credentials are filled in, my .NET backend sends back NotFound() (404 status code). I'm trying to handle this reponse by using try/catch block in my angular code but at this point i still see the 404 error in the console even if i use this try/catch block. How can I make sure that this HTTP error isn't logged?

Angular

try {
  this.store.dispatch(loginAction({ request }))
} catch (error) {
  console.log("Error: "   error)
}

.NET

[HttpPost("login")]
public async Task<ActionResult<ServiceResponse<String>>> Login(UserLoginDto request)
{
    var response = await _authRepo.Login(request.Username, request.Password);

    // Check the response
    if (!response.Success) return NotFound(response);
    return Ok(response);
}

Console

enter image description here

CodePudding user response:

The store.dispatch method just sends the action to the registered reducers and effects. Surrounding the dispatch with a try catch does nothing (unless you dispatch an action without a type). If you want to catch the 404, you need to do this in the effect.

See the docs https://ngrx.io/guide/effects#handling-errors for more info.

CodePudding user response:

Return NoContent() instead of NotFound() in the .NET API

We use NotFound() with the pages that not found, and use NoContent() as a search result.

The full description of all status:

https://learn.microsoft.com/en-us/dotnet/api/system.net.httpstatuscode?view=net-7.0

After this change we need to discus the possible empty result inside the effect instead of error.

  • Related