Skip to content

Instantly share code, notes, and snippets.

@alisdair
Created September 27, 2017 14:23
Show Gist options
  • Save alisdair/4efd86ec04d5d675614b792581a73d83 to your computer and use it in GitHub Desktop.
Save alisdair/4efd86ec04d5d675614b792581a73d83 to your computer and use it in GitHub Desktop.
Reject vs Catch: Failures and Exceptions Part 2
import Ember from 'ember';
const { RSVP } = Ember;
const success = (time) => new RSVP.Promise((resolve) => setTimeout(resolve, time));
const failure = (time) => new RSVP.Promise((_, reject) => setTimeout(reject, time));
export default Ember.Controller.extend({
logs: ['Initialized'],
init() {
Ember.onerror = function(error) {
alert(`Ember onerror: ${error}`);
};
},
actions: {
perform(error) {
let webhookPromises = [150, 200, 100].map(success);
if (error === 'rejection') {
webhookPromises.push(failure(500));
}
this.set('logs', ['Waiting for webhooks…']);
return RSVP.all(webhookPromises)
.then(() => {
this.get('logs').pushObject('Secondary task…');
})
.then(() => {
if (error === 'exception') {
throw new Error('whoops');
}
this.get('logs').pushObject('Success!');
})
.catch((error) => this.get('logs').pushObject(`Error occurred! ${error}`));
}
}
});
<h1>Promises</h1>
<p>
Try out three scenarios below. Because we're using a <code>catch</code> handler, both error cases are managed by our error handler.
</p>
<ul>
<li><b>Succeed</b> will trigger some webhooks, then do some secondary task, then complete.</li>
<li><b>Webhook fail</b> will simulate error handling from a promise rejection.</li>
<li><b>Exception fail</b> will simulate exception handling from within the secondary task block.</li>
</ul>
<hr>
<p>
Logs:
</p>
<ul>
{{#each logs as |log|}}
<li>{{log}}</li>
{{/each}}
</ul>
<p>
<button {{action "perform"}}>Succeed</button>
<button {{action "perform" "rejection"}}>Webhook fail</button>
<button {{action "perform" "exception"}}>Exception fail</button>
</p>
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment