0

I need to execute a function which is defined in controller in load-time, in order to gain json data from another place right after page is loaded.
I've tried to call the func immediately within controller, now i feel it was bad idea.
When something bad is happen and exception is raised - the controller stops working.

Well, not big surprise, but at the moment i don't have idea how work it out.
Ofcourse, i can wrap possible dangerous code in try-catch, but that's definetely not best solution imho.
Here's the sample code:

app.controller("ServerStatusCtrl",
    function($scope) {
        $scope.reloadFunc = function()
        {
            throw "dat bad exception";
        }
        $scope.reloadFunc(); // Let's pretend that it's needed 2 call this function in load-time.
    });

And example on jsfiddle

VirtualVoid
  • 1,005
  • 3
  • 17
  • 25
  • 1
    Why do you say that using try-catch is not a good solution ? That is the principle itself of the exceptions, though. – Blackhole Jun 14 '13 at 13:36
  • 1
    This is exactly what a try..catch block should be used for. I think a better question is why are errors being thrown. The code should be able to handle whatever json is returned. – Mark Meyer Jun 14 '13 at 13:36
  • Thanx.. but it is really not a solution for me, more like a kludge. As been shown in example at jsfiddle, i have a handler for uncaught exceptions. That's pretty enough. – VirtualVoid Jun 15 '13 at 10:57

2 Answers2

1

I advice you to use $q's way of notifying that something happen: return promise and reject it after something wrong happen.

This is the way how exception handling is done in async/promise way.

General idea is:

  1. Instead of returning result, function should return promise
  2. When you have your data ready (loaded from server) you resolve promise
  3. If something bad happen you reject it.

    function someFunc() { var d = $q.defer(); do.somethingAsync(function(result) { if (somethingWrong) d.reject(result); else d.resolve(result); }); return d.promise; }

And in controller:

   $scope.myData = someFunc().then(function ok(result) { return ok.data; }, function faled() { handle...});

This gives a good control on error handling/recovery.

Valentyn Shybanov
  • 19,331
  • 7
  • 66
  • 59
  • Hm.. looking nice, didn't know. Thank you. That reminded me Jquery. But seems i've found solution myself, a bit easier way. – VirtualVoid Jun 15 '13 at 11:01
0

Found easier solution for this.
Just discovered a ngInit directive which solved the whole problem.
Also, i think that module.run(fn) would be also applicable for this kind of tasks.

VirtualVoid
  • 1,005
  • 3
  • 17
  • 25