从Angular 2 http获取错误消息 [英] Get error message from Angular 2 http

查看:1293
本文介绍了从Angular 2 http获取错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务中包含以下代码

I have the following code in my service

myService.ts

makeHttpGetRequest(url){

        return Observable.interval(config.SUPERVISOR_REFRESH_INTERVAL * 1000)
            .switchMap(() => this.http.get(url))
            .map(res => res.json())
            .timeout(config.REQUEST_TIMEOUT * 1000, new Error('Time out occurred'))

    }

在我的组件文件中,

myComponent.ts

ngOnInit(){
        this._myService.makeHttpGetRequest(myurl)
            .subscribe(
                data => {
                    this.supervisorServers = data;
                    }

                },
                error => {
                    this.error = true;
                    console.log(error); //gives an object at this point
                    this.showError(error);
                }
            );
    }

我想在以下情况下打印错误消息: Invailid网址。
当我打印错误时,我得到一个对象(可能是响应对象),如下所示:

I want to print the error message in case of for e.g. Invailid url. When I print the error, I get an object (probably response object) like the following:

Object { _body: error, status: 200, statusText: "Ok", headers: Object, type: 3, url: null }

如果我打开它,我找不到错误信息。是否有更好的方法来获取precies错误消息?

If I open this, I cannot find the error message. Is there a better way to get precies error messages?

推荐答案

即使在这种情况下,错误也包含在响应正文中。请参阅错误事件处理程序onError函数:

The error is contained in the body of the response even in this case. See the error event handler onError function:

  • https://github.com/angular/angular/blob/master/modules/@angular/http/src/backends/xhr_backend.ts#L96

您可以使用响应中的json方法访问它:

You can access it using the json method on the response:

error => {
  this.error = true;
  console.log(error.json()); //gives the object object
  this.showError(error.json());
}

修改

我对此问题进行了更多调查。事实上,你无法得到确切的信息。我的意思是 net :: ERR_NAME_NOT_RESOLVED 。 XHR不提供它。也就是说,你可以看到XHR的状态 0 。这可能暗示发送请求时请求有问题(实际上并未发送)。

I investigated a bit more this issue. In fact, you can't have the exact message. I mean the net::ERR_NAME_NOT_RESOLVED. XHR doesn't provide it. That said, you can see that the status of XHR is 0. This could be an hint that there was a problem the request when sending the request (it's not actually sent).

error => {
  (...)
  var err = error.json();
  var status = err.currentTarget.status;
  (...)
}

看到这个问题:

  • XMLHttpRequest() & net::ERR_NAME_NOT_RESOLVED

这篇关于从Angular 2 http获取错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆