코딩, 개발에 대한 기록 저장소

AngularJS의 페이지 로딩 에러 처리하기 (Page loading error in angularJS)



하이브리드 앱을 AngularJS로 작업하다 보니 네트워크 처리가 여간 귀찮은게 아니었습니다.

그래서 최상위 controller에서 에러에 대한 처리를 하고 각 controller에서는 네크워크 에러 여부만 전달하는 방식으로 고민 하다보니 $exceptionHandler라는 것을 알게 되었습니다.

저의 경우 초반에 exceptionHandler에서 exception를 받기는 하는데 다시 $state 처리가 되지 않아서 고생했습니다. 아마도 exceptionHandler에서는(혹은 사용하는 위치에 따라?) injector를 사용해야 정상동작을 하는 것 같습니다.
그렇지 않으면...많이 보셨던 아래 문구를 또 보시게 됩니다.
```
Unknown provider: eProvider <- e <- $exceptionHandler <- $rootScope <- $q <- $exceptionHandler
```

아래는 예제 코드 입니다.

```

    angular.module('MyApp').factory('$exceptionHandler', ['$injector', function ($injector) {
        return function (exception, cause) {
            console.log("======================= exception", exception);
            console.log("======================= cause", cause);
            var state = $injector.get('$state');
            state.go("signin");
        };
    }]);

```

각 controller 에서는 http 통신결과가 200이 아닐 경우 exception를 던지고 끝
```
if (res.status == 200) {
 if (typeof callback == "function") {
  callback(res.data);
 }
}
else {
 // http 통신이 200이 아닐 경우 처리
 $exceptionHandler(res);
}
```