samedi 4 novembre 2017

Ember centralised error handling within an Action

Inside an Ember controller I have a number of actions which perform data events (create update and delete) on the store.

Each of these requests has the same error handling logic which is repeated many times. If there a way of centralising this error logic?

  1. Given this logic will be used by many routes, what would be the best location in Ember for it to live?
  2. How can the context be preserved so this is still available to send toast type of messages to the DOM ?

Here is an example of what I have now

createEntryRecord() {
  // This action is a 'create' button on a modal
  set(this, 'isLoadingModal', true);  // shows loading spinner
  let dbid = this.get('dbidModal');
  let type = this.get('entryModalType');

  this.get('store').createRecord('my-store', {
    type,
    dbid
  })
  .save()
  .then((record) => {
    get(this, 'flashMessages').success(`Created`);  // Toast message
  })
  .catch((e) => {
    // Begin of the error handling logic
    let errors = get(e, 'errors');
    if (errors.length) {
      errors.forEach(err => {
        let field = err.source.pointer.split("/").pop();
        get(this, 'flashMessages').danger(`${field}: ${err.detail}`);
      });
    } else {
      let message = get(e, 'message');
      get(this, 'flashMessages').danger(`${message}`);
    }
  })
  .finally(() => {
    set(this, 'isLoadingModal', false);  // stop the loading spinner
    set(this, 'isEntryModalShown', false);
  });
},




Aucun commentaire:

Enregistrer un commentaire