【问题标题】:Angular + Core API: How to intercept request response error bodyAngular + Core API:如何拦截请求响应错误体
【发布时间】:2019-02-13 03:07:29
【问题描述】:

我想截取错误信息而不是错误名称。

目前在 Angular 中使用的拦截器:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                this.authenticationService.logout();
                location.reload(true);
            }               
            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
}

但它只返回“错误请求”而不是来自 API 的错误消息。

public IActionResult Login([FromBody]UserModel user)
{ 
    if (userRepository.CheckIfUserExists(user.Username))
    {
        if (userRepository.CheckIfPasswordIsCorrect(user))
        {
            return new JsonResult(userRepository.GetUser(user));
        }
        else
        {
            return BadRequest("Test");
        }
    }
    else
    {
        return BadRequest("Test");
    }
}

【问题讨论】:

    标签: c# .net angular .net-core asp.net-core-webapi


    【解决方案1】:

    这是问题的解决方案,而不是:

    const error = err.error.message || err.statusText;
    

    我使用了不同的管道:

    const error = err.error.message || err.error;
    

    【讨论】:

      【解决方案2】:

      通常你不需要使用像 HttpInterceptor 这样的低级 API,因为 HttpClient 已经提供了足够的函数来处理 HTTP 错误。

      Http 客户端服务:

      export namespace My_WebApi_Controllers_Client {
      @Injectable()
      export class Account {
          constructor(@Inject('baseUri') private baseUri: string = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/', private http: HttpClient) {
          }
      
          /**
           * POST api/Account/AddRole?userId={userId}&roleName={roleName}
           */
          addRole(userId: string, roleName: string): Observable<HttpResponse<string>> {
              return this.http.post(this.baseUri + 'api/Account/AddRole?userId=' + encodeURIComponent(userId) + '&roleName=' + encodeURIComponent(roleName), null, { observe: 'response', responseType: 'text' });
          }
      

      在您的应用代码中:

                  this.service.addRole(this.userId, roleName)
                  .pipe(takeWhile(() => this.alive))
                  .subscribe(
                  (data) => {
                      //handle your data here
                  },
                  (error) => {
                      error(error);
                  }
      

      详细错误处理:

          error(error: HttpErrorResponse | any) {
                  let errMsg: string;
          if (error instanceof HttpErrorResponse) {
              if (error.status === 0) {
                  errMsg = 'No response from backend. Connection is unavailable.';
              } else {
                  if (error.message) {
                      errMsg = `${error.status} - ${error.statusText}: ${error.message}`;
                  } else {
                      errMsg = `${error.status} - ${error.statusText}`;
                  }
              }
      
              errMsg += error.error ? (' ' + JSON.stringify(error.error)) : '';
          } else {
              errMsg = error.message ? error.message : error.toString();
          }
          //handle errMsg
      
      }
      

      你可以去 HttpErrorResponse 的细节来更具体地处理错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-22
        • 2018-01-07
        • 2017-11-07
        • 2020-09-25
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        相关资源
        最近更新 更多