Using StackTrace.js with Angular.js - javascript

I'm implementing a logger for my whole MEAN.js project. I have a server side logger that works well, and I've set an endpoint to receive a POST request with an exception to log a client error. I'm using StackTrace.js for client side error logging, but I'm getting some errors; now I'm using StackTrace's error-stack-parser and still getting errors. I'm using a decorator on Angular's $exceptionHandler to achieve this:
$provide.decorator("$exceptionHandler",
function($delegate, traceService, $log, $window) {
return function(exception, cause) {
$delegate(exception, cause);
try {
var errorMessage = exception.toString();
var stackTrace = traceService.
parse(exception).
then(function(stackFrames) {
$.ajax({
type: 'POST',
url: '/logger',
contentType: 'application/json',
data: angular.toJson({
url: $window.location.href,
message: errorMessage,
type: 'exception',
stackFrace: stackFrames,
cause: cause || ''
})
}).fail(function() {
$log.warn('POST request failed');
});
}).catch(function(error) {
$log.warn('Error StackTrace');
});
} catch (loggingError) {
$log.warn('Error server-side logging failed');
$log.log(loggingError);
}
};
});
traceService is an Angular service that acts as a proxy for StackTrace/error-stack-parser functions. traceService.parse is equivalent to ErrorStackParser.parse. traceService is implemented as:
angular.module('core').factory('traceService', function() {
return {
parse: ErrorStackParser.parse
};
});
I've put this decorator code on the Angular app bootstrap, and I'm testing by throwing an error on a controller. When I run the app I get this error on the client console:
Error server-side logging failed
angular.js:13708 TypeError: this.parseV8OrIE is not a function
at Object.ErrorStackParser$$parse [as parse] (error-stack-parser.js:70)
at application.js:22
at invokeLinkFn (angular.js:9816)
at nodeLinkFn (angular.js:9215)
at compositeLinkFn (angular.js:8510)
at publicLinkFn (angular.js:8390)
at lazyCompilation (angular.js:8728)
at updateView (viewDirective.ts:278)
at Object.configUpdatedCallback [as configUpdated] (viewDirective.ts:226)
at configureUiView (view.ts:164)
It would seem like this is an issue with error-stack-parse; I can't seem to find any articles regarding this issue, so I'm sure it's something I'm doing wrong, the way I'm testing or something else. Can any provide some insight as to why this is failing?
Edit
I modified the code following Caramiriel's comment. It seems like I need to add all functions from error-stack-parser to my service. This is traceService:
angular.module('core').factory('traceService', function() {
return {
parse: ErrorStackParser.parse,
parseV8OrIE: ErrorStackParser.parseV8OrIE,
extractLocation: ErrorStackParser.extractLocation
};
});
Now I'm getting this error:
TypeError: StackFrame is not a constructor
at Object.<anonymous> (http://localhost:3000/lib/error-stack-parser/error-stack-parser.js:105:24)
at Array.map (native)
at _map (http://localhost:3000/lib/error-stack-parser/error-stack-parser.js:22:26)
at Object.ErrorStackParser$$parseV8OrIE [as parseV8OrIE] (http://localhost:3000/lib/error-stack-parser/error-stack-parser.js:95:20)
at Object.ErrorStackParser$$parse [as parse] (http://localhost:3000/lib/error-stack-parser/error-stack-parser.js:70:29)
at http://localhost:3000/application.js:22:11
at invokeLinkFn (http://localhost:3000/lib/angular/angular.js:9816:9)
at nodeLinkFn (http://localhost:3000/lib/angular/angular.js:9215:11)
at compositeLinkFn (http://localhost:3000/lib/angular/angular.js:8510:13)
at publicLinkFn (http://localhost:3000/lib/angular/angular.js:8390:30)

It looks like you are using error-stack-parser without its dependency on the stackframe project.
You'll get that dependency automatically if you use npm or bower.

Related

serverless framework with json parsing error

I use serverless framework with javascript.
my code is:
import { App } from '../lib/App';
export const hello = (event, context, cb) => {
context.callbackWaitsForEmptyEventLoop = false;
// This resolved promise would be be in the application library code in a real-world application and provide the results
App.handleFirst(event) // eslint-disable-line promise/catch-or-return
.then(result => ({
statusCode: 200,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(result)
}))
.asCallback(cb);
return;};
inside App.js
import BbPromise from 'bluebird';
const THE_MESSAGE = 'Hello from the webpack 4 sample';
export class App {
static handleFirst(event) {
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event
};
console.info(myDemoResult);
return BbPromise.resolve(myDemoResult);
}
I use fellow command to deploy it.
set SLS_DEBUG=*
severless deploy
my error is:
Syntax Error -------------------------------------------
Unexpected token A in JSON at position 0
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
Stack Trace --------------------------------------------
SyntaxError: Unexpected token A in JSON at position 0
SyntaxError: Unexpected token A in JSON at position 0
at JSON.parse (<anonymous>)
at BbPromise.try (F:\workspace\svlecma\node_modules\serverless-webpack\lib\packagers\npm.js:61:47)
at tryCatcher (F:\workspace\svlecma\node_modules\bluebird\js\release\util.js:16:23)
at Function.Promise.attempt.Promise.try (F:\workspace\svlecma\node_modules\bluebird\js\release\method.js:39:29)
at Utils.spawnProcess.catch.then.then.depJson (F:\workspace\svlecma\node_modules\serverless-webpack\lib\packagers\npm.js:61:35)
at tryCatcher (F:\workspace\svlecma\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:694:18)
at _drainQueueStep (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:17:14)
From previous event:
at PluginManager.invoke (C:\Users\sheng\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:390:22)
at PluginManager.spawn (C:\Users\sheng\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:408:17)
at ServerlessWebpack.BbPromise.bind.then.then.then (F:\workspace\svlecma\node_modules\serverless-webpack\index.js:102:51)
at runCallback (timers.js:694:18)
at tryOnImmediate (timers.js:665:5)
at processImmediate (timers.js:647:5)
at process.topLevelDomainCallback (domain.js:121:23)
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Issues: forum.serverless.com
Your Environment Information -----------------------------
OS: win32
Node Version: 10.10.0
Serverless Version: 1.31.0
my serverless.yml is here:
https://gist.github.com/thinksource/9fd0c8728df2195b7110b3be04aec2ae
why json first element error? how Can I see the json string?
After seeing your serverless.yml file, I believe that the issue may well be in the webpack.config.js file. It may be worth trying changing your custom section, and putting quotes around: 'webpack.config.js'. Like:
custom:
webpack:
webpackConfig: 'webpack.config.js'
includeModules: true
I think that the issue is in your App.js class here:
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event
};
You have a invalid JSON structure; where the object event is being passed, it is not being given a key/name. You probably want something like:
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event: event
};
Also your constant THE_MESSAGE is not inside your App class. You should move it inside the App classes {..} like this:
export class App {
static get THE_MESSAGE() { return 'Hello from the webpack 4 sample'; }
...

Meteor Router crashing - Cannot call method 'filters' of undefined

I have a page that I want the user to not be able to access unless they have a certain property. I have defined a filter as such:
Meteor.Router.filters({ //line 24
isX: function(page) {
if(Roles.userIsInRole(this.userId, ['X'])) {
return page;
} else {
return '/error';
}
}
});
Meteor.Router.filter(isX, {only : 'xPage'});
this code exists in my router.js file. When I try to compile it I get the following error:
\.meteor\packages\meteor-tool\1.1.4\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\fibers\future.js:245
throw(ex);
^
TypeError: Cannot call method 'filters' of undefined
at app\lib\router.js:24:15
at app\lib\router.js:70:3 //end of file
at \.meteor\local\build\programs\server\boot.js:222:10
at Array.forEach (native)
at Function._.each._.forEach (\.meteor\packages\meteor-tool\1.1.4\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\underscore\underscore.js:79:11)
at \.meteor\local\build\programs\server\boot.js:117:5
Exited with code: 8
Your application is crashing. Waiting for file change.
I'm at a loss because this is pretty much straight out of the examples for iron router.
I'm not sure where you are getting Meteor.Router.filters with regards to iron:router. You can do something very similar to what you need with an onBeforeAction though.
var isX = function() {
if (Roles.userIsInRole(this.userId, ["X"])) {
this.next();
}
else {
this.redirect("/error");
}
};
Router.onBeforeAction(isX, {
only: ["xPage"]
});
Router.route("/xPage", {
name: "xPage",
action: function() {
this.render("xPage");
}
});

Node-ACl throws uhandled rejection error

i am using ACL module in my express application.At the start of the server i define some roles and their permissions using the acl.allow() function.
But it logs in a error saying undefined rejection type.The error vanishes on giving a callback with error param.But i am not very sure about what is throwing the error and how it should be handled.
My snippet code which i am using is :
var aclmodule = new acl(new acl.mongodbBackend(config.db.URL, "accesscontrol_"));
aclmodule.allow([
{
roles:['rolea'],
allows:[
{resources:['a','b'], permissions:['*']}
]
},
{
roles:['roleb','rolec'],
allows:[
{resources:['a'], permissions:['view']}
]
},
{
roles:['rolec'],
allows:[
{resources:['o'], permissions:['view','edit']}
]
}
]);
});
The error logged in console is :
Unhandled rejection TypeError: undefined is not a function
at D:\user\web\myapp-web\node_modules\acl\lib\mongodb-backend.js:119:15
at D:\myapp\web\myapp-web\node_modules\acl\node_modules\async\lib\async.
js:607:21
at D:\myapp\web\myapp-web\node_modules\acl\node_modules\async\lib\async.
js:246:17
at iterate (D:\myapp\web\myapp-web\node_modules\acl\node_modules\async\l
ib\async.js:146:13)
at async.eachSeries (D:\myapp\web\myapp-web\node_modules\acl\node_module
s\async\lib\async.js:162:9)
at _asyncMap (D:\myapp\web\myapp-web\node_modules\acl\node_modules\async
\lib\async.js:245:13)
at Object.mapSeries (D:\myapp\web\myapp-web\node_modules\acl\node_module
s\async\lib\async.js:228:23)
at Object.async.series (D:\myapp\web\myapp-web\node_modules\acl\node_mod
ules\async\lib\async.js:605:19)
at Object.MongoDBBackend.end (D:\myapp\web\myapp-web\node_modules\acl\li
b\mongodb-backend.js:35:11)
at Object.tryCatcher (D:\myapp\web\myapp-web\node_modules\acl\node_modul
es\bluebird\js\main\util.js:26:23)
at Object.ret [as endAsync] (eval at (D:\myapp\web\myapp-web
\node_modules\acl\node_modules\bluebird\js\main\promisify.js:163:12),
Is config.db.URL a string? If so, this is the cause of your errors. The line it is failing on is (in mongodb-backend.js):
self.db.collection(... -- it is saying that .collection() is undefined. (Which would make sense if "self.db" were only a string.)
Node-acl expects a database instance when creating a new mongodbBackend, like it says in the docs -- for example:
mongoose.connection.on('connected', function() {
var myAcl = new acl(new acl.mongodbBackend(mongoose.connection.db));
});

Object #<Object> has no method 'User'

everyone. I have a problem with my code and Meteor 0.9.4
Here is my code:
Server/publications.js
Meteor.publish('getUsers', function () {
var loggedInUser = Meteor.User();
if (Roles.userIsInRole(loggedInUser, ['admin'])) {
return Meteor.users.find({}, {fields: {
_id: 1,
emails: 1,
roles: 1
}});
}
this.stop();
return;
});
Lib/router.js
Router.map(function() {
this.route('dashboardUsers', {
layoutTemplate: 'dashboardLayout',
path: "/dashboard/users",
waitOn: function() {
return Meteor.subscribe('getUsers');
}
});
});
When I run meteor app, I have the following error:
=> App running at: http://localhost:3000/
I20141019-18:21:50.827(4)? Exception from sub 8CRiG3Jmdv4mohPhd TypeError: Object #<Object> has no method 'User'
I20141019-18:21:50.949(4)? at null._handler (app/server/publications.js:3:31)
I20141019-18:21:50.950(4)? at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
I20141019-18:21:50.950(4)? at _.extend._runHandler (packages/ddp/livedata_server.js:943)
I20141019-18:21:50.950(4)? at _.extend._startSubscription (packages/ddp/livedata_server.js:769)
I20141019-18:21:50.951(4)? at _.extend.protocol_handlers.sub (packages/ddp/livedata_server.js:582)
I20141019-18:21:50.951(4)? at packages/ddp/livedata_server.js:546
If you have a look at the docs for Meteor.user, you'll see it works everywhere except publish functions. You need to do:
var loggedInUser = Meteor.users.findOne(this.userId);
The error your getting is because of the upper-case 'u' in Meteor.User it should be Meteor.user.
However, as David Weldon pointed out you'll need to use Meteor.users.findOne(this.userId) inside of publish functions.
For anyone else running into the error Object #<Object> has no method 'user' when trying to access Meteor.user() be sure you have the accounts-base package.

Angular resource testing: $httpBackend.flush() cause Unexpected request

I want to test angularjs resource.
'use strict';
/**
* AddressService provides functionality to use address resource in easy way.
*
* This is an example usage of method:
*
* `get`:
*
var a = AddressService.get({id: '1'},
function (data) {
// Work here with your resource
}
);
*
*/
App.factory('AddressService', function ($resource, $rootScope) {
var url = [
$rootScope.GLOBALS.API_PATH,
$rootScope.GLOBALS.API_VERSION,
'models/address/:id'
].join('/'),
actions = {
'get': {
method: 'GET',
params: {id: '#id'}
}
};
return $resource(url, {}, actions);
});
I created the test:
'use strict';
var $httpBackend;
describe('Service: AddressService', function () {
beforeEach(module('myApp'));
beforeEach(inject(function ($injector) {
var url_get = 'api/v1/models/address/5';
var response_get = {
address_line_1: '8 Austin House Netly Road',
address_line_2: 'Ilford IR2 7ND'
};
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(url_get).respond(response_get);
}));
describe('AddressService get test', function () {
it('Tests get address', inject(function (AddressService) {
var address = AddressService.get({ id: '5'});
$httpBackend.flush();
expect(address.address_line_1).toEqual('8 Austin House Netly Road');
expect(address.address_line_2).toEqual('Ilford IR2 7ND');
}));
});
});
I am not experienced with angular very well.
I have set jasmine in karma.config.js.
AngularJS v1.0.6
Yoeman and Grunt manage project.
I try grunt test
Running "karma:unit" (karma) task
INFO [karma]: Karma server started at http://localhost:8080/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 27.0 (Linux)]: Connected on socket id RFFUY5bW8Hb5eTu0n-8L
Chrome 27.0 (Linux) Service: AddressService AddressService get Tests get address FAILED
Error: Unexpected request: GET views/home.html
No more request expected
at Error (<anonymous>)
at $httpBackend (/home/bart/y/projects/x/frontend/app/components/angular-mocks/angular-mocks.js:910:9)
at sendReq (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:9087:9)
at $http (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:8878:17)
at Function.$http.(anonymous function) [as get] (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:9021:18)
at $q.when.then.then.next.locals (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:7394:34)
at wrappedCallback (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:6797:59)
at wrappedCallback (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:6797:59)
at /home/bart/y/projects/x/frontend/app/components/angular/angular.js:6834:26
at Object.Scope.$eval (/home/bart/y/projects/x/frontend/app/components/angular/angular.js:8011:28)
Error: Declaration Location
at window.jasmine.window.inject.angular.mock.inject (/home/bart/y/projects/x/frontend/app/components/angular-mocks/angular-mocks.js:1744:25)
at null.<anonymous> (/home/bart/y/projects/x/frontend/test/spec/services/userdata/AddressService.js:32:30)
at null.<anonymous> (/home/bart/y/projects/x/frontend/test/spec/services/userdata/AddressService.js:31:5)
at /home/bart/y/projects/x/frontend/test/spec/services/userdata/AddressService.js:5:1
..................................................................
Chrome 27.0 (Linux): Executed 67 of 67 (1 FAILED) (0.343 secs / 0.179 secs)
Warning: Task "karma:unit" failed. Use --force to continue.
If I remove $httpBackend.flush() in test. Test is passing. But I am getting undefined from address. I saw examples: example all use the flush() But only I get silly exception: Error: Unexpected request: GET views/home.html
views/home.html is my view in project directory. I have no idea how solve my problem I could not find any solution. Am I missing the point somehow?
Can anybody see mistake in my code? All suggestions will be appreciate.
EDIT
I have found that I need to use this:
$httpBackend.when('GET', /\.html$/).passThrough();
But another problem is I am getting:
TypeError: Object #<Object> has no method 'passThrough'
the error is caused by your test attempting to load the main page for your app. Since you have not told the test to expect this server call, an error is returned. See the documentation for $httpBackend for clarification on this point.
Your $templateCache workaround is designed for unit testing directives not anything else. You were quite close with:
$httpBackend.when('GET', /\.html$/).passThrough();
Since you don't need to do anything with the actual template file it's a safe and simple work around to add this to your beforeEach() block.
$httpBackend.whenGET(/\.html$/).respond('');
This stops you getting the TypeError you had.
TypeError: Object #<Object> has no method 'passThrough'
I had the same issue in my unit tests after upgrading to a new version of Angular JS and using respond('') worked fine.
I have finally found solution:
I tried to follow this: other post
So I added $templateCache:
'use strict';
var $httpBackend;
describe('Service: AddressService', function () {
beforeEach(module('myApp'));
beforeEach(inject(function ($injector, $templateChache) {
$templateCache.put('views/home.html', '.<template-goes-here />');
var url_get = 'api/v1/models/address/5';
var response_get = {
address_line_1: '8 Austin House Netly Road',
address_line_2: 'Ilford IR2 7ND'
};
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(url_get).respond(response_get);
}));
describe('AddressService get test', function () {
it('Tests get address', inject(function (AddressService) {
var address = AddressService.get({ id: '5'});
$httpBackend.flush();
expect(address.address_line_1).toEqual('8 Austin House Netly Road');
expect(address.address_line_2).toEqual('Ilford IR2 7ND');
}));
});
});

Categories

Resources