【问题标题】:How to deal with http status codes other than 200 in Angular 2如何在Angular 2中处理200以外的http状态码
【发布时间】:2016-08-31 08:39:15
【问题描述】:

现在我做http请求的方式(借用this answer)是这样的:

POST(url, data) {
        var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
        headers.append("Content-Type", 'application/json');

        if (authtoken) {
        headers.append("Authorization", 'Token ' + authtoken)
        }
        headers.append("Accept", 'application/json');

        var requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: this.apiURL + url,
            headers: headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(requestoptions))
        .map((res: Response) => {
            if (res) {
                return { status: res.status, json: res.json() }
            }
        });
    }

这很好用,除了如果返回的状态码不是 200 则 angular2 将失败。例如,如果用户想要发布内容并且服务器返回 400,则 angular 2 将抛出异常:

未捕获的异常:[object Object]

我怎样才能避免这种情况?我想在我的应用中处理这些状态代码,以增强用户体验(显示错误等)

【问题讨论】:

标签: typescript angular


【解决方案1】:

是的,您可以像这样使用 catch 运算符处理并根据需要显示警报,但首先您必须像这样导入 Rxjs

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

您也可以处理 .map 函数时由 catch 块抛出的错误(带有 err 块),

像这样 -

...
.subscribe(res=>{....}
           err => {//handel here});

更新

根据任何状态的要求,无需检查特定状态,您可以尝试以下操作:-

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

【讨论】:

  • 是否可以不必将每个状态代码都写为条件?就像只返回状态一样,然后我的组件可以确定如何处理这些状态代码。
  • 是的,您可以只返回错误而不检查状态,这取决于您要如何处理错误块。
  • 你能编辑一下吗?用你现有的例子很难做到这一点。
  • 我已经更新了我的答案检查一次@SebastianOlsen
  • 似乎使用订阅方法对我有用。谢谢!
【解决方案2】:

包含所需的导入,您可以在 handleError 方法中做出决定 错误状态会给出错误代码

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2018-05-01
    • 2020-07-14
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多