$ httpProvider.interceptors的自定义错误消息

时间:2017-02-15 03:27:28

标签: javascript angularjs user-interface

我们已实施以下

function Inteceptors($httpProvider) {
    'ng-inject';
    $httpProvider.interceptors.push('ErrorInterceptor');
    $httpProvider.interceptors.push('LoadingInterceptor');
}

function ErrorInteceptor($q, MyNotificationService) {
    'ng-inject';

    return {
        responseError: function(response) {
            var msg = JSON.stringify(response.data);
            var status = response.status;
            console.log('in ErrorInterceptor', response);
            if (response.status === -1) {
                status = null;
                msg = 'An unspecified error occured while trying to make a request'
            }
            var notification = {
                type: 'error',
                status: status,
                msg: msg
            };
            MyNotificationService.add(notification);
            return $q.reject(response);
        }
    };
}

这允许拦截404和500之类的错误,并且正在向用户提示消息。

但是,在某些情况下我想使用我自己的自定义错误消息。

例如,当我有一个调用API的函数时:

    this.list = function() {
        return $http({
                method: 'GET',
                url: myendpoint
            })
            .then(function(response) {
                    return response.data;
                },
                function(err) {
                    return [];
                });
    }

在404的情况下,响应如下所示:

- Object
  -- config: Object
- data: Object
- headers: (name)
  - status: 404
  - statusText: "Not Found"
- __proto__: Object

所以如果API返回404,那么拦截器现在正在显示响应数据,这是"未找到"响应中的状态为404.status

所以现在的消息是

(404) {"detail": "Not found"}

这很丑陋而且没有帮助!

我想提供自己的自定义消息,我将如何实现?

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,那么您希望从ErrorInteceptor()函数返回自定义错误。您收到同样的错误,因为您要返回response,即return $q.reject(response);,请尝试从您的服务返回自定义消息。

试试这个

 return {
        responseError: function(response) {
            var status = response.status;
            console.log('in ErrorInterceptor', response);
            if (response.status === -1) {
                status = null;
                msg = 'An unspecified error occured while trying to make a request'
            }
            var notification = {
                type: 'error',
                status: status,
                msg: msg
            };
            MyNotificationService.add(notification);
            return $q.reject(response.statusText);// this is what you should return
        }
    };
相关问题