如何显示来自 angular 8 typescript 订阅的错误消息?

Posted

技术标签:

【中文标题】如何显示来自 angular 8 typescript 订阅的错误消息?【英文标题】:How to display error message from angular 8 typescript subscribe? 【发布时间】:2021-05-25 05:22:00 【问题描述】:

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

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

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

【问题讨论】:

你试过console.log(error.error)吗? @MihaiAlexandru-Ionut 是的,我试过了。不工作。 您可以登录error并将内容粘贴到这里吗? 【参考方案1】:

您可以使用状态码拦截错误。将它们发送到 C# 后端

c#

try

  ...

catch (UserDetailAlreadyRegisteredException ex)

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return BadRequest("The user is already registered");
   

service.ts

我假设您使用的是 Angular 9+。使用RXJS throwError 拦截并发送error observable。

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

component.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 8 typescript 订阅的错误消息?的主要内容,如果未能解决你的问题,请参考以下文章