Search code examples
angularangular-httpclient

Problem getting HttpErrorResponse from httpClient


I got a problem using angular and a .net backend. In my application Im trying to return http status 403 Forbidden when the user tries to do something that is not allowed.

In my backend Controller

[HttpDelete("{id}")]
public async Task<ActionResult<UserProject>> DeleteUserProject(int id)
{
    ...
    // Insufficient permissions"
    return Forbid();
}

in my angular service

deleteProjectUser(userProjectId: number): Observable<any> {
  return this.http.delete(`${environment.apiUrl}/UserProjects/${userProjectId}`, { observe: 'response' })
    .pipe(
      tap(
        userProject => {
          // works
          return userProject;
        },
        error => {
          // Expecting HttpErrorResponse with error.status == 403
          console.log(error);
        }));
}

and in my angular component

leaveProject(userProjectId: number) {
    console.log('remove user-project with id: ' + userProjectId);
    this.projectService.deleteProjectUser(userProjectId)
      .pipe(first())
      .subscribe(
        data => {
          // everything worked
        },
        error => {
          // Expecting propagated HttpErrorResponse
          console.log(error);
        });
}

I can see that the backend returns 403 with no body as expected in chrome. But I dont get a HttpErrorResponse from http.delete when the backend returns 403 with the Forbid() method. I get a TypeError.

Output in the chrome console

remove user-project with id: 1202
userProjectService.leaveProject userProjectId: 1202
DELETE http://localhost:5000/api/UserProjects/1202 403
TypeError: Cannot read property 'message' of null
    at CatchSubscriber.selector (error.interceptor.ts:20)
    at CatchSubscriber.error (catchError.js:29)
    at XMLHttpRequest.onLoad (http.js:2477)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:39680)
    at ZoneDelegate.invokeTask (zone-evergreen.js:390)
    at Zone.runTask (zone-evergreen.js:168)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:465)
    at invokeTask (zone-evergreen.js:1603)
    at XMLHttpRequest.globalZoneAwareCallback (zone-evergreen.js:1640)
TypeError: Cannot read property 'message' of null

Ok, but if I dont use the Forbid() method. I can set a body so I changed my backend to

return new ObjectResult("Forbidden") { StatusCode = 403 };

Then I get the string "Forbidden" as error in my service and component. But still no HttpErrorResponse from HttpClient. What is wrong? I want a HttpErrorResponse and the http status code from HttpClient.delete if somethings goes wrong.


Solution

  • Your stack trace shows that you have an error.interceptor in your application. The TypeError occurs in that part of your system. You can check line 20 in your interceptor to see more details about the issue you are trying to solve.