angular - Angular 中的 HTTP 错误处理

标签 angular http

我需要通知用户 POST、GET 或 PUT 方法是否正确执行。 有什么好的办法吗?

例如组件中用于发送数据的 POST 方法:

SendData() {
    this.srv.PostData(this.user).subscribe(
      data => {
        console.log('Success', data);
      },
      error => console.log('Error', error)
    );
  }

在 Http 服务中我有:

PostData(userdata: User) {
    return this.http.post<any>(this.url + this.postDataString, userdata);
  }

我想要的是: - 获取执行 POST 或 PUT 的信息(如何获取 200 OK 或其他 HTTP 应答的通知?) - 获取 GET 方法正确执行的信息(如何获取 404 Not Found 或其他 HTTP 错误代码的通知?)

感谢您的回答。

问候

编辑: 我添加的是:

import { Injectable } from '@angular/core';
import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpErrorResponse,
    HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError, switchMap, filter, take, tap } from 'rxjs/operators';
//import 'rxjs/add/operator/do';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(catchError(error => {

            if (error instanceof HttpErrorResponse && (error.status === 401)) {
                sessionStorage.setItem('accessToken', '');
            } else if (error instanceof HttpErrorResponse && (error.status === 500 )) {
               console.log('500 Internal Server Error', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 502 )) {
               console.log('502 Bad Gateway', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 503 )) {
               console.log('503 Service Unavailable', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 504 )) {
               console.log('504 Gateway Timeout', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 0 )) {
               console.log('503 Service Temporarily Unavailable', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 200 )) {
                console.log('200 OK', '', { timeOut: 5000 });
                 return throwError(error);
            } else  {
                return throwError(error);
            }
        }),
        tap((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse && event.status === 200) {
              console.log('SUCCESS - 200');
            }
          })
        );
    }
}

现在的问题是,我如何调用并给出有关我调用的方法的正确消息,例如: - 获取用户数据 - 为经理获取数据 - ETC。 ?

所以问题是我如何知道现在正在使用哪个 HTTP 方法和 URL?

另一个问题: 如果出现任何问题,我需要向用户发送 snackbar 或警报。您对此类功能有什么建议?我应该在哪里调用它?

最佳答案

创建拦截器 http.intercepter.ts

import { Injectable } from '@angular/core';
import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, switchMap, filter, take } from 'rxjs/operators';
import 'rxjs/add/operator/do';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(error => {
            if (error instanceof HttpErrorResponse && (error.status === 401)) {
            } else if (error instanceof HttpErrorResponse && (error.status === 500 )) {
               console.log('500 Internal Server Error');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 502 )) {
               console.log('502 Bad Gateway');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 503 )) {
               console.log('503 Service Unavailable');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 504 )) {
               console.log('504 Gateway Timeout');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 0 )) {
               console.log('503 Service Temporarily Unavailable');
                return throwError(error);
            } else  {
                return throwError(error);
            }
        }));
    }
}

并将其注入(inject)到应用程序模块中,如下所示。

import { HttpErrorInterceptor } from './core/http.intercepter';
providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }]

关于angular - Angular 中的 HTTP 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59243709/

相关文章:

javascript - 按对象键查询 Firestore

ios - 在 iOS Safari 上调试添加到主屏幕的 Web 应用程序

javascript - 类型 A 缺少类型 B 的以下属性 : a, b

c# - 如何解析在 MVC Controller 中收到的 JSON

http - 在 JBoss AS 7 中自定义 HTTP 代码和错误消息

javascript - 在 Angular 中读取对象内的数组

angular - typescript ( Angular )日期时间到日期

php - WordPress中的HTTP错误500,这是15天内的第二次

javascript - Chrome 会发出两次请求的原因

http - 使用 header 过滤代理响应 header