【问题标题】:HTTP error message from API not showing in Angular component来自 API 的 HTTP 错误消息未显示在 Angular 组件中
【发布时间】:2020-06-20 00:55:55
【问题描述】:

我有一个 ExpressJS 后端端点,它(形象地)是这样的:

function myFunction(req, res, next) {
  if (someErrorCondition)
    res.status(400).json({message: "Something went wrong."});
  else {
    myBackendService.someFunc.then(res.status(200).json({message: "Success!"}))
     .catch(err => next(err))
  }
}

从一个 Angular 前端组件,我通过订阅请求这个端点:

this.myFrontendService.someFunc().subscribe(
  res => {
    console.log(res);
  },
  error => {
    console.log(error);
  });

当调用正确运行时(即状态 200),将 JSON 对象 {message: "Success!"} 记录(如预期)为 res 对象。但是当它失败时,它会记录:

Http failure response for http://localhost:4000/myRoute/myFunction: 400 Bad Request

而且我在任何地方都没有收到“出现问题”的消息。我从后端发送的。错误代码在 Angular 中的处理方式是否不同?

此外,当我使用 cURL 调用后端端点时,两条消息都按预期作为 JSON 对象返回。

编辑:myFrontService 类声明如下所示:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class FrontendService {

  constructor(private http: HttpClient) { }

  someFunc() {
    return this.http.put(`localhost:4000/myRoute/myFunction`, {data: "here's some data"});
  }
}

【问题讨论】:

  • this.myFrontendService.someFunc() 是什么样的?
  • @E.Maggini 我编辑了问题:)

标签: angular http error-handling


【解决方案1】:

错误可以是不同类型的(服务器错误、网络错误)。看看documentation

您可以创建一个根据类型提取错误消息的方法。

component.ts

//...
this.myFrontendService.someFunc().subscribe(
  res => {
    console.log(res);
  },
  error => {
    this.handleError(error);
  });


private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) //client side error
  {
    console.error('An error occurred:', error.error.message);
  } 
  else  //server side error
  {
    //console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
    let resp = JSON.parse(error.error);
    console.log(resp.message);//Since you returned a {message: ...} object from API
  }
}

您也可以直接在服务中添加处理程序,例如在文档链接中

【讨论】:

  • 我尝试使用您提供的代码,但是当我在 else 条件下取消注释 console.error() 时,error.status 和 error.error 都未定义。记录错误我从我的问题中得到相同的消息,因为它是一个字符串,所以 JSON.parse() 会引发错误。感谢您的回复。
【解决方案2】:

我发现了问题。我在身份验证过程中使用 HttpInterceptor 来过滤和处理 401 和 403 代码(与权限错误相关),然后对于所有其余代码(如问题中的 400),我只是抛出了 err .message 而不是 err.error.message,前者是我在问题中得到的字符串:'Http failure response for... ',后者是从后端发送的实际消息:“出了问题。”。

这里是 HttpInterceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(err => {
        if ([401, 403].indexOf(err.status) !== -1) {
            // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
            this.authService.logout();
            location.reload(true);
        }

        const errorFromBackend = err.error.message; // Something went wrong.
        const errorGeneric = err.message; // Http failure response for...
        return throwError(errorFromBackend);
    }))
}

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 2014-09-10
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多