2014-11-06 31 views
1

我熟悉MEAN堆棧。到目前爲止,使用非常熟悉的方法從後端拉取數據是一件輕而易舉的事情 - 使用服務來進行$ http調用,並將數據返回給Angular controller作用域。現在我有點卡住了,這是我的快遞代碼:集成的角度,快速錯誤處理

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 
    }); 
    }); 
} 

然後,我設置了角渲染視圖:

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

但是,我怎麼打發err對象從快遞到角ErrorController的範圍?

請指教。

回答

0

UPDATE

在再次閱讀你的問題,我不知道如果我回答您的查詢的所有部分。這裏有幾點需要注意的地方:

  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狀態和/或主體內容,然後使用裏面的東西像一個$ rootScope.emit()或簡單的警報() responseError函數顯示錯誤。這裏是從angularjs文檔中挑選的代碼片段:

$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'); 

希望這有助於!