如何在Angular 2中处理200以外的http状态代码
现在我执行http请求的方式(从此答案中借用)是:
Right now the way I do http requests (borrowed from this answer) is this:
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将抛出异常:/p>
This works fine, except for the fact that angular2 will fail if the status code returned is anything else than 200. For example, if a user wants to post something and the server returns 400, angular 2 will throw the exception:
未捕获的异常:[对象对象]
uncaught exception: [object Object]
如何避免这种情况?我想在我的应用中处理这些状态代码,以增强用户体验(显示错误等)
How can I avoid this? I'd like to handle these status codes in my app in order to enhance user experience (show errors, etc)
是的,您可以使用catch操作符进行处理,并根据需要显示警报,但首先必须以这种方式导入Rxjs
>
Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs
for the same like this way
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块),
also you can handel error (with err block) that is throw by catch block while .map
function,
像这样-
...
.subscribe(res=>{....}
err => {//handel here});
更新
根据任何状态的需要而无需检查特定状态,您可以尝试以下操作:-
Update
as required for any status without checking particluar one you can try this: -
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)} );