AngularJS - Use Toaster Notification for Custom Exception Handling and Logging - javascript

Using AngularJS Toaster for notification handling.
Now for custom exception handling, defined in index.html like below
<toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast-top-right'}"></toaster-container>
Using it in controller like below for custom exception
myService.serviceName().then(function (data) {
//do some processing
}).catch(function (error) {
toaster.pop({
type: 'error',
title: 'Custom exception!'
});
});
How can I use Angularjs-Toaster inside the decorator of
$exceptionHandler ?
How can I use Angularjs-Toaster for logging specific errors ?
How can I use a common service for toaster notification for
success,error and other messages ?

AngularJS has its own exception handler. You can override it with a
Decorator that helps you to extend the functionality of an object in
AngularJS.
Move the code of showing toastr to custom exception handler, and in your service throw an exception which is handled by custom exception handler.
So your service looks like these,
myService.serviceName().then(function (data) {
//Handle success
}).catch(function (error) {
// throw exception from catch handler
throw new Error(error.msg);
});
Custom Exception Handler for showing toastr messages.
angular.module('exceptionHandlingApp')
.config(function($provide) {
$provide.decorator('$exceptionHandler',
['$delegate', 'toastr', function extendExceptionHandler($delegate, toastr) {
return function (exception, cause) {
exception.message = '[Error: ]' + exception.message;
// Use toastr service to show toastr msg.
toastr.pop({
type: 'error',
title: exception.message
});
$delegate(exception, cause);
};
}]);
});

Related

Sendind SMS from IONIC not working with $cordovaSms plugin

I am using smsCordova plugin to send sms from my ionic application but getting the error that "SMS is not defined".
I had used the cordovaSms plugin in $ionicPlatform.ready() function.
Here is my code which i am using to send the SMS :-
//use verifyNumber service
verifyNumberService.verify()
.then(
function (result) {
if (result == "Successfully data save...") {
//alert and navigate to profile Info state
$ionicPopup.alert({
title: 'Registered',
template: 'Thanks For Signup'
});
$ionicPlatform.ready(function() {
alert("in device ready function")
sendOtp();
});
$state.go('profileInfo');
}
This is the function to sendOtp() :-
function sendOtp() {
alert("inside send otp");
$cordovaSms
.send('+919765293765', "Hi there",{})
.then(function () {
// Success! SMS was sent
alert("success")
console.log('Success');
}, function (error) {
// An error occurred
alert("error");
console.log(error);
});//then
alert("send otp");
}
Azhar Khan,
If we wants to use the send sms request in cordova, then
1. we need to install this plugin in you app :
cordova plugin add https://github.com/cordova-sms/cordova-sms-plugin.git
2.Need to add that plugin instance($cordovaSms) in Controler function :
.controller('ThisCtrl', function($cordovaSms) {
});
Now we can send the sms throw that plugin using this code inside you controler :
document.addEventListener("deviceready", function () {
$cordovaSms.send('mobile_number', 'SMS Message', options)
.then(function() {
alert(SMS sent )
}, function(error) {
alert(Problem in sending SMS)
});
});
Thats all we need for sending SMS to any number in ionic
Have a happy code day.

Server side account creation error

I have been trying to get server side account user creating to work but I have come across an issue with the check() method I am using server side. (I am using simple-schema for this)
When the password is empty, this causes check() to throw an error, and rightly so. However, this is a server-side error and I am not quite sure how to propagate this to the client to be caught and dealth with.
The exception that I can see from my browser console is as follows:
Exception while simulating the effect of invoking 'createUserAccount' Meteor.makeErrorType.errorClass {message: "Match error: One or more properties do not match the schema.", path: "", sanitizedError: Meteor.makeErrorType.errorClass, errorType: "Match.Error", stack: (...)…} Error: Match error: One or more properties do not match the schema.
at SimpleSchema.condition (http://localhost:3000/packages/aldeed_simple-schema.js?8fda161c43c0ba62801a10b0dfcc3eab75c6db88:2450:11)
at checkSubtree (http://localhost:3000/packages/check.js?ac81167b8513b85b926c167bba423981b0c4cf9c:255:17)
at check (http://localhost:3000/packages/check.js?ac81167b8513b85b926c167bba423981b0c4cf9c:67:5)
at Meteor.methods.createUserAccount (http://localhost:3000/both/methods/accounts.js?c418120e76666f0ca774a281caafc39bc2c3a59d:4:27)
at http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:4244:25
at _.extend.withValue (http://localhost:3000/packages/meteor.js?81e2f06cff198adaa81b3bc09fc4f3728b7370ec:949:17)
at _.extend.apply (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:4235:54)
at _.extend.call (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:4113:17)
at Object.Template.PasswordRegister.events.submit form (http://localhost:3000/client/views/shared/accounts/accounts.js?ac573d92938a2b3d6107ea19e50065f7ac5d41b3:36:20)
at null. (http://localhost:3000/packages/blaze.js?efa68f65e67544b5a05509804bf97e2c91ce75eb:3147:18)
Here is how my client code looks like :
Template.PasswordRegister.events({
'submit form': function(event, template) {
event.preventDefault();
var user = {
email: template.find('#email').value,
password: template.find('#password').value
};
Meteor.call('createUserAccount', user, function(error) {
if (error) {
console.log("CONSOLE : " + error);
//TODO DO SOMETHING
// return alert(error.reason);
} else {
Meteor.loginWithPassword(user.email, user.password, function(error) {
if (error) {
console.log("CONSOLE : " + error);
//TODO DO SOMETHING
// return alert(error.reason);
}
});
}
});
}
});
and here is my server side code:
Meteor.methods({
createUserAccount: function(user) {
// Important server-side check for security and data integrity
check(user, Schema.registration);
var email = user.email;
var password = user.password;
this.unblock();
return Accounts.createUser({
email: email,
password: password
});
}
});
I've tried wrapping client-side code with a normal try catch block but didn't make any difference; that console error still shows.
As the error message says, you have a method stub for 'createUserAccount' defined on the client. It is that client stub that is throwing the exception.
Wrap the method shown with if (Meteor.isServer) to keep it from running on the client.
if (Meteor.isServer ){
Meteor.methods({
createUserAccount: function (user) { ... }
});
}
If that doesn't work search your project for the client code defining the method stub.
To clarify what is happening I have made a meteorpad with a method incorrectly stubbed on the client that throws the error you see in the browser console. I have then added a second method, 'creatUserAccount1', which is only defined on server. When this second method is called, its error is handled by callback and does not cause an exception. I think that is the behaviour you want.

angular-spinner | Skipping $http.post error handling

I am using angular-spinner to intercept all http request from my application and show a loading spinner.
Relevant code:-
//spinner configuration START
myApp.factory('spinnerInterceptor', ['usSpinnerService', function(usSpinnerService) {
return {
request: function(config) {
usSpinnerService.spin('spinner-1');
return config;
},
response:function(config){
usSpinnerService.stop('spinner-1');
return config;
},
responseError:function(config){
usSpinnerService.stop('spinner-1');
return config;
}
};
}]);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('spinnerInterceptor');
}]);
//spinner configuration END
Except starting/stopping the spinner , I am simply just returning the config object.
Problem:-
One of my POST RESTful endpoint, return 404 status with an error message and still success handler of the $http block gets executed? Why?
$http({
method : 'POST',
url : url,
params :paramsJson,
data : _data
}).success(function(data,status) {
// THIS GET EXECUTED AFTER SPINNER INTERCEPTOR WITH STATUS 404 !!!!
}).error(function(data,status) {
// THIS BLOCK I EXPECT TO RUN IN CASE OF 404 or any non 2XX response
});
Before success/error handler of the $http, the spinnerInterceptor do get executed, which is somewhere playing with the error handling of the promise that gets returned.
When running my code without the spinner interceptor, everything works as expected.
Please help me fix this.
The problem here is "responseError" interceptor. you need to reject request in this block. else error is already handled in you interceptor so what ever you return here will go to success block.
The corrected interceptor code is:
responseError:function(config){//here we get response rename it
usSpinnerService.stop('spinner-1');
return $q.reject(config);
}
You can refer to Error Handling in angular for more info.
I had to develop an "automatic" spinner recently in a project. I used $q promises to signal success / error on the interceptor methods and it worked fine. My code was:
(function () {
'use strict';
function httpBusyInterceptor($q) {
function _responseError (response) {
//Hide spinner code
return $q.reject(response);
}
function _response (response) {
//Hide spinner code
return response || $q.when(response);
}
function _request (config) {
//Show spinner code
return config || $q.when(config);
}
return {
request: _request,
response: _response,
responseError: _responseError
};
}
httpBusyInterceptor.$inject = ['$q'];
angular.module('common.ui').factory('httpBusyInterceptor', httpBusyInterceptor);
})();

How can I analyse my JS program to ensure a particular method is always called with 2 arguments?

We're using promises in an AngularJS project and want to ensure that the then method is always called with 2 arguments, the 2nd being an error handler, like so:
$http.get(url).then(function () {
console.log('hooray!');
}, function (error) {
console.log('boo! error');
});
We're using jshint on the project. Can that perform this analysis?
Some calls to then do not require an error handler, i.e. in a chain of handlers:
$http.get(url1).then(function () {
console.log('hooray!');
return $http.get(url2);
}).then(function () {
console.log('hooray again! all our data loaded');
}, function (error) {
console.log('boo! error in one of our 2 requests');
});
We could mark these up using jshint's /* jshint ignore:start */ comments or similar.

Setting up Airbrake on an Ember application

How do you set up Airbrake such that it gets context information from unhandled Javascript errors that occur in an Ember application?
Assuming you've included Airbrake-js you can hook on Ember's onerror handler and push errors.
Ember.onerror = function(err) { // any ember error
Airbrake.push(err);
//any other error handling
};
Ember.RSVP.configure('onerror',function(err){ // any promise error
Airbrake.push(err);
console.error(e.message);
console.error(e.stack);
//any other generic promise error handling
};
window.onerror = function(err){ // window general errors.
Airbrake.push(err);
//generic error handling that might not be Airbrake related.
};
You can see more options of different parameters of the data sent in the airbrake-js GitHub repository docs.
I don't know if this answers your question, but I hope it helps.
To handle server thrown errors you can define an "error" function in the application's route and push it in Airbrake:
App.ApplicationRoute = Ember.Route.extend({
actions: {
error: function(error) {
// handle the error
Airbreak.push(error)
}
}
});
Moreover, if you catch errors somewhere else and have the same handling, you can make a mixin and pass the error:
App.ErrorHandlerMixin = Ember.Mixin.create({
handleError: function(error){
//make different stuff
Airbreak.push(error)
}
});
App.ApplicationRoute = Ember.Route.extend(App.ErrorHandlerMixin, {
actions: {
error: function(error, transition) {
this.handleError(error);
}
}
});
App.ApplicationController = Ember.ObjectController.extend((App.ErrorHandlerMixin, {
someFunction: function () {
this.handleError(randomError);
}
});
This way you have all the error handling in a single place.

Categories