2

If I understand correctly (promises API is very confusing), any error occurred in a promise is suppressed, so the following code:

$http.post(...)
    .then(data => {
      if (data.noGood) {
        return $q.reject();
      } else {
        // Some bug.
        var a = {};
        return a.a.a > 3;
      }
    })
    .catch(error => {
      console.error('bad data');
    });

is buggy, as badData is not necessarily true if 'bad data' is logged).

The desired behaviour for me is to see a console error upon every real runtime error, and leave handling rejections to me. Am I missing something here? What is the correct approach?

Checking if the error is Error on each catch block seems tedious.

Uri
  • 25,622
  • 10
  • 45
  • 72
  • Other promise implementation are [much better debuggable](http://stackoverflow.com/questions/25827234/how-to-debug-javascript-promises) – Bergi Jul 05 '16 at 11:04

1 Answers1

0

Unless the rejection was explicitly constructed from Error class or its child, rejections can be differentiated by their types.

.catch(error => {
  if (!(error instanceof Error))
    console.error(error)
});

Exceptions from $q promises are handled by $exceptionHandler service and logged by default, even if they are caught with catch. Without error instanceof Error type check console.error(error) will result in logging them twice.

Despite reject and throw are used interchangeably most of the times, for $q promises it makes sense to reject rejection reasons and throw errors as Error objects to keep this scheme working.

Community
  • 1
  • 1
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • In a jasmine test I'm seeing errors suppressed (not logged) when there is a `catch` after `then`. It seems the link you provided is talking about angular expression errors, i.e. in HTML templates. – Uri Jul 05 '16 at 10:55
  • @Uri It talks about any kind of JS errors that may happen inside Angular app callbacks (except SyntaxError that cannot be caught). The question doesn't touch upon Jasmine or testing. Any way, this is not true. When ngMock is loaded, it brings its [own implementation of $exceptionHandler](https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider) that rethrows exceptions from $exceptionHandler to Jasmine. [see here](http://plnkr.co/edit/9RkyIQ1KYuFQi5QEM9n9?p=preview). This behaviour is configurable with $exceptionHandlerProvider. – Estus Flask Jul 05 '16 at 11:28