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

3
  • 1
    Why do you say that using try-catch is not a good solution ? That is the principle itself of the exceptions, though.
    – Blackhole
    Commented Jun 14, 2013 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
    Commented Jun 14, 2013 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. Commented Jun 15, 2013 at 10:57

2 Answers 2

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.

1
  • Hm.. looking nice, didn't know. Thank you. That reminded me Jquery. But seems i've found solution myself, a bit easier way. Commented Jun 15, 2013 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.