1

I have a config load function that loads some data from a json file and resolves a promise with it.

When I call the load function I'm wondering what the better way is to handle errors. From what I understand and can there are two options.

public config: any = this.configProvider.load()
    .then(data => this)
    .then(error => console.error(error));

versus

public config: any = this.configProvider.load()
    .then(data => this)
    .catch(function(err){
        console.log(err);
    }
Augie Luebbers
  • 308
  • 1
  • 2
  • 15

3 Answers3

2

This code is not correct:

public config: any = this.configProvider.load()
    .then(data => this)
    .then(error => console.error(error));

It will not catch any errors. Errors are promises that are rejected. What you need is this:

public config: any = this.configProvider.load()
    .then(data => this, error => console.error(error))

Pass the function that catches rejected promises as a second parameter.

But the approach with catch is more readable and intuitive to me:

public config: any = this.configProvider.load()
    .then(...)
    .then(...)
    .then(...)
    .catch(function(err){
        console.log(err);
    }

But you can achieve the same with the following:

public config: any = this.configProvider.load()
    .then(...)
    .then(...)
    .then(..., function(err){
        console.log(err);
    });
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
1

.catch is the good option here.

.catch catches errors from the process of loading up the json / invalid json, double .then execute regardless if error occurs. so if you get no errors, the second .then will still execute

user2167582
  • 5,986
  • 13
  • 64
  • 121
0

They both achieve the same goal of logging your error. However, the context does not change when you step inside of an arrow function. The value of this will change inside a function block. For example, if you need to use keys associated with the object enclosing your function, you may be better off using a function block, since, then you can refer to the enclosing object by using the this keyword. Additionally, as far as I know, using the .catch at the end of your chain will catch any errors encountered in the promise chain up until that point. However using .then will catch an error of the immediately preceding .then block and not any from before.