2

Am I allowed to add a catch method in my model hook? i.e. something like this:

model(params) {
    return this.store.findRecord('shop', params.slug)
    .catch( () => 
        this.transitionTo('welcome.shops.index'))
    }
}

My goal is to route the user whenever he entered the incorrect slug. If there is a better approach to my desire behaviour please suggest it. Would appreciate any help, thanks.

Patsy Issa
  • 11,113
  • 4
  • 55
  • 74
Mikelemuel
  • 378
  • 1
  • 3
  • 15
  • https://stackoverflow.com/questions/36233353/ember-js-how-to-handle-error-with-ds-store-findrecord-method – Jeff Mar 01 '18 at 03:22
  • 3
    Yes, you are. I couldn't think of a better way – Jeff Mar 01 '18 at 03:28
  • 2
    An alternative would be to use the error event: https://guides.emberjs.com/v3.0.0/routing/loading-and-error-substates/#toc_the-code-error-code-event – locks Mar 05 '18 at 01:19

1 Answers1

1

You are allowed to do so, but I would not consider it best practice. Let's dig a little bit deeper in what you are doing:

this.store.findRecord('shop', params.slug) returns a Promise. Promise.catch() returns a Promise (and registers a function to be executed if the promise rejects).

So your model hook returns the Promise from findRecord but also registers a function to be executed if this Promise rejects.

You should use Route's error event to execute logic if your model Promise rejects.

jelhan
  • 6,149
  • 1
  • 19
  • 35