<div class="container"> {{#if error}} <div class="alert alert-danger" role="alert"> <button type="button" class="close alert-close" aria-label="Close"><span aria-hidden="true">×</span></button> {{error}} </div> {{/if}} {{>Template.dynamic template=content}} </div>
Next, I'll use postaljs to subscribe to the 'error' topic. When an error is received, a ReactiveVar will be set with the error message, which in turn will cause the template to show the error UI:
Template.mainLayout.onRendered(function() { var template = this; this.postalSubError = postal.subscribe({ topic: 'error', callback: (data) => { var errorMessage = data.message || 'There was an error performing an operation. Please try again later.'; this.error.set(errorMessage); } }); });
Now any part in the website can report errors by publishing an event. For example, below is how to handle errors when an ingredient is deleted:
Template.ingredientsListPart.events({ 'click .ingredient-delete': function(event, template) { event.preventDefault(); var ingredientId = this['_id']; IngredientMethods.removeIngredient.call({ id: ingredientId }, methodReturnHandler); } }); function methodReturnHandler(err, res) { if (err) { postal.publish({ topic: 'error', data: { error: err } }); } }
That is all there is to it. You can see in the screen capture below how the experience looks like. One important thing to note is how when the user clicks the delete button, the item is immediately removed from the client but a couple of seconds later the error is displayed and the item returns to the list. This is due to Meteor's eventual consistency design. The server method actually runs on the client first, modifying the local ingredients list and updating the UI. After that the server method is asynchronously invoked, and if it turns out that it fails, the error is triggered and more importantly the changes to the client collection are reverted.
You can check the code up to this point by using this commit or visit the live demo.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.