catch没有捕获Angular 2的错误

时间:2017-05-04 17:33:30

标签: angular

如果响应是401,403,那么我有一个服务,我正在尝试返回一个Observable,或者像这样的500:

  post(url, data) {
        let headers = new Headers();
        headers = this.createAuthorizationHeader(headers);
        return this.http.post(url, data, {
            headers: headers
        }).catch(this.catchAuthError(this));
    }

catchAuthError方法:

    private catchAuthError (self: HttpUtil) {
        // we have to pass HttpService's own instance here as `self`
        return (res: Response) => {

            if (res.status === 401 || res.status === 403 || res.status === 500) {

                //TODO: route the user to the login page again and make a 500 ERROR page
                // if not authenticated
                console.log("ERROR: "+res);

                this.relogin.showDialog();

            }
            return Observable.throw('Not authenticated: '+res);
        };
    }

我不确定为什么该方法没有被触发,但网络标签(chrome)自然会告诉我我得到了哪个错误。但是,控制台未显示console.log("ERROR: "+res);

2 个答案:

答案 0 :(得分:1)

您的代码应该更像这样:

post(url, data) {
    let headers = new Headers();
    headers = this.createAuthorizationHeader(headers);
    return this.http.post(url, data, { headers: headers })
           .catch((err)=> this.catchAuthError(err)); //** use arrow notation here
}

private catchAuthError (error) {
    console.log(error); //**then depending on your error object fill the below lines
    if (error.status === 401 || error.status === 403 || error.status === 500) {

        console.log("ERROR: "+ (error.message || error) );

        this.relogin.showDialog();
     }

     return Observable.throw('Not authenticated: '+error);
}

答案 1 :(得分:0)

您的输入参数类型错误

确保您正在导入

import 'rxjs/add/operator/catch';

修改您的代码,如下所示

 post(url, data) : Observable<Response> {
        let headers = new Headers();
        headers = this.createAuthorizationHeader(headers);
        return this.http.post(url, data, {
            headers: headers
        }).map(res => res.json())
        .catch(this.catchAuthError);
    }



private catchAuthError(res: Response) {
            if (res.status === 401 || res.status === 403 || res.status === 500) {

            //TODO: route the user to the login page again and make a 500 ERROR page
            // if not authenticated
            console.log("ERROR: "+res);

            this.relogin.showDialog();

        }
        return Observable.throw('Not authenticated: '+res);

    }

<强> LIVE DEMO