【问题标题】:Integrated Angular, Express error handling集成 Angular、Express 错误处理
【发布时间】:2014-11-07 03:02:17
【问题描述】:

我开始熟悉 MEAN 堆栈。到目前为止,使用非常熟悉的方法从后端提取数据是轻而易举的事——使用服务进行 $http 调用并将返回的数据分配给 Angular 控制器范围。现在我有点卡住了,这是我的 Express 代码:

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.send({
      message: err.message,
      error: err
    });
  });
}

然后我设置 Angular 来渲染视图:

$routeProvider
  //...
  .otherwise({
    templateUrl: 'ui/error.html',
    controller: 'ErrorController'
  });

但是,如何将 err 对象从 Express 传递到 Angular ErrorController 的作用域?

请指教。

【问题讨论】:

    标签: angularjs express angular-ui-router


    【解决方案1】:

    更新

    再次阅读您的问题时,我不确定我是否回答了您的所有问题。这里有几个开放点:

    1. 您是如何调用服务器端 API 的?如果您使用的是 $http,那么您将在控制器中使用它,如下所示:

      $http.get('/something')
          .success(function(data) { ... })
          .error(function(error) { ... }); // This is where you'll receive the error sent from the server
      
    2. 以下部分(我之前回答过的部分)为您提供了一种通用方法来处理从 Angular 应用程序内的任何位置连接 API 时出现的任何错误。


    您需要编写一个 http 拦截器,您可以在其中检查响应的 http 状态和/或正文内容,然后在 responseError 函数中使用 $rootScope.emit() 或简单的 alert() 来显示错误。这是从 angularjs 文档中挑选的代码 sn-p:

    $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
      return {
        // optional method
        'request': function(config) {
          // do something on success
          return config;
        },
    
        // optional method
       'requestError': function(rejection) {
          // do something on error
          if (canRecover(rejection)) {
            return responseOrNewPromise
          }
          return $q.reject(rejection);
        },
    
        // optional method
        'response': function(response) {
          // do something on success
          return response;
        },
    
        // optional method
       'responseError': function(rejection) {
          // do something on error
    
          ////////////////////////////////////////////////////////
          // >>>>>>>> check for rejection.status here <<<<<<<<< //
          ////////////////////////////////////////////////////////
    
          if (canRecover(rejection)) {
            return responseOrNewPromise
          }
          return $q.reject(rejection);
        }
      };
    });
    
    $httpProvider.interceptors.push('myHttpInterceptor');
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 2018-07-05
      • 2015-10-03
      • 1970-01-01
      • 2017-12-10
      相关资源
      最近更新 更多