Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reject vs Catch: Failures and Exceptions Part 1
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!');
},
(error) => this.get('logs').pushObject(`Error occurred! ${error}`));
}
}
});
<h1>Promises</h1>
<p>
Try out three scenarios below. The <b>exception</b> case does not trigger 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