Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何显示angular 8 typescript订阅的错误消息?_C#_Angular_Typescript_Webapi - Fatal编程技术网

C# 如何显示angular 8 typescript订阅的错误消息?

C# 如何显示angular 8 typescript订阅的错误消息?,c#,angular,typescript,webapi,C#,Angular,Typescript,Webapi,我有一个带有以下自定义异常的c sharp后端: try { ... } catch (UserDetailAlreadyRegisteredException ex) { return BadRequest("The user is already registered"); } 此异常返回“用户已注册”,并且它在后端工作正常 但是,当我从前端调用它时,它不会显示错误消息,我只得到[object,object]。当我尝试记录这个对象时,里面没有任何有用的东西

我有一个带有以下自定义异常的c sharp后端:

try
{
  ...
}
catch (UserDetailAlreadyRegisteredException ex)
{
  return BadRequest("The user is already registered");
}   
此异常返回“用户已注册”,并且它在后端工作正常

但是,当我从前端调用它时,它不会显示错误消息,我只得到[object,object]。当我尝试记录这个对象时,里面没有任何有用的东西。我在前端是这样称呼它的:

  onRegisterSubmit(user: User): void {
    this.userService.registerNewUser(user).subscribe(() => {
      this.toastr.success('Registration Completed', 'Success');
    },
      error => {
        // console.log(error._body);
        this.toastr.error(error, 'Failed');
      }
    );
  }

有没有办法将消息从后端传递到前端?

您可以使用状态代码截获错误。用C#后端发送

c#

服务.ts

onRegisterSubmit(user: User): void {
    this.userService.registerNewUser(user).subscribe(() => {
      this.toastr.success('Registration Completed', 'Success');
    },
      (error) => {
        // console.log(error._body);   **//this block gets activated at error**
        this.toastr.error(error, 'Failed');
      }
    );
  }
我假设您使用的是angular 9+。使用RXJS throwError拦截并发送可观察到的错误

    import { throwError } from 'rxjs';
    
registerNewUser(user){

return this._http.post("url", data)
      .pipe(catchError(this.errorHandler));
}


    public errorHandler(errorResponse: HttpErrorResponse) { 
      //write your own error I am returning response as such
        return throwError(errorResponse);
      }
组件。ts

onRegisterSubmit(user: User): void {
    this.userService.registerNewUser(user).subscribe(() => {
      this.toastr.success('Registration Completed', 'Success');
    },
      (error) => {
        // console.log(error._body);   **//this block gets activated at error**
        this.toastr.error(error, 'Failed');
      }
    );
  }

你试过
console.log(error.error)
?@MihaiAlexandru Ionut是的,我试过了。不起作用。您可以只记录
错误
并将内容粘贴到此处吗?