Globle error filter in node js - node.js

I am working on node from last 2-3 months on a project. Now I want to handle errors from a single point in node. For example : I have several api functions in my project. Many of them are taking _id as an api input. I need to parse this id using mongoose objectid before using in query. Now if the format of _id is not valid, it will throw the casting error. It could be handled by mongoose object isvalid property. But my purpose is that, at any place if it is not handled in code I want to catch the error and log it to my log file and send a common message like 'error occurs' to the UI. I want to add a common error handler for all the api that do the logging and error handling for my api, like we use .net MVC - error handler filer through the application.
I have tried using domain. But in domain.on('error',func(err){}); it is not working. I put my api functions call in domain.run();
If any body have any suggestion for me, please let me know.

Take a look at the domain module, if your app powered by express you can use the package - express-domain-middleware

Related

Independent NPM library that validates request based on swagger file

We are building APIs using Swagger, AWS API gateway and Lambda functions with NodeJS. The API gateway will do the request validation, however as per the design, the lambda functions need to re-validate the request object as an API Gateway Proxy Request Event. This makes sense as in theory we can reuse the lambda functions by invoking them via other event source (e.g. SNS).
Therefore we need an NodeJS tool which can validate the request (not only body but also params, etc) based on the swagger spec - exactly what the swagger-tools and a few other tools (e.g. swagger-request-validator) are doing, but not as a middleware.
I did some search but could not find one, also looked into swagger-tools source code, reckon its validation component was written in the way that cannot be easily used separately.
Any suggestion is welcome. Thanks in advance.
You can use swagger-model-validator.
var Validator = require('swagger-model-validator');
var swaggerFile = require("./swagger.json");
const validator = new Validator(swaggerFile);
console.log(validator.validate({
name: 'meg'
}, swaggerFile.definitions.Pet, swaggerFile.definitions, true).GetErrorMessages())
This outputs:
[ 'photoUrls is a required field' ]
validator.validate returns an object, so you can also check if the returned object contains anything under the errors attribute. It should be as simple as
if (validator.validate({
name: 'meg'
}, swaggerFile.definitions.Pet, swaggerFile.definitions, true).errors) {
// do something with error
}
I have used Swagger's sample JSON for this answer.

Feathers JS nested Routing or creating alternate services

The project I'm working on uses the feathers JS framework server side. Many of the services have hooks (or middleware) that make other calls and attach data before sending back to the client. If I have a new feature that needs to query a database but for a only few specific things I'm thinking I don't want to use the already built out "find" method for this database query as that "find" method has many other unneeded hooks and calls to other databases to get data I do not need for this new query on my feature.
My two solutions so far:
I could use the standard "find" query and just write if statements in all hooks that check for a specific string parameter that can be passed in on client side so these hooks are deactivated on this specific call but that seems tedious especially if I find this need for several other different services that have already been built out.
I initialize a second service below my main service so if my main service is:
app.use('/comments', new JHService(options));
right underneath I write:
app.use('/comments/allParticipants', new JHService(options));
And then attach a whole new set of hooks for that service. Basically it's a whole new service with the only relation to the origin in that the first part of it's name is 'comments' Since I'm new to feathers I'm not sure if that is a performant or optimal solution.
Is there a better solution then those options? or is option 1 or option 2 the most correct way to solve my current issue?
You can always wrap the population hooks into a conditional hook:
const hooks = require('feathers-hooks-common');
app.service('myservice').after({
create: hooks.iff(hook => hook.params.populate !== false, populateEntries)
});
Now population will only run if params.populate is not false.

How to handle Node js app errors to prevent crashing

I am new to node and what I would call, real server-side programming (vs PHP). I was setting up a user database with MongoDB, Mongoose and a simple mongoose user plugin that came with a schema and password stuff to use. You can add validation to Mongoose for your fields like so
schema.path('email').validate(function (email) {
if (this.skipValidation) return true
return email.trim().length
}, 'Please provide a valid email')
(this is not my code). I noticed though when I passed an invalid or blank email, .trim() failed and the entire server crashed. This is very worrisome to me because things like this don't happen in your good ol' WAMP stack. If you have a bug, 99.9% of the time it's just the browser that is affected.
Now that I am delving into lower level programming, do I have to be paranoid about every incoming variable to a simple function? Is there a tried-and-true error system I should follow?
Just check before using the variable with trim, if it is !null for example:
if(!email) {
return false;
}
And if you want to run your app forever, rather use PM2.
If you are interested in running forever, read this interesting post http://devo.ps/blog/goodbye-node-forever-hello-pm2/
You may consider using forever to keep your node.js program running. Even it crashes, it restarts automatically and the error is logged as well.
Note: Although you could actually catch all exceptions to prevent the node.js from crashing, it is not recommended.
One of our strategies is to make use of Node.js Domain to handle errors - http://nodejs.org/api/domain.html
You should set up a error logging node modules like Winston, once configured produces useful error/exceptions.
Have a look in this answer for how to catch error within your node implementation, though specific to expressjs but relevant.
Once you catch exceptions, it prevents unexpected crashes.

How to get metadata from MongoDB with Breeze

Currently I have a project using WebAPI and EF with Breeze, it works fine with Metadata stuffs for validation on server but when migrating to NodeJS and MongoDB, I get stuck for trying get Metadata from MongoDB. I checked out zza BMEAN app but I just saw on this project:
app.get('/breeze/Breeze/Metadata', getMetadata);
function getMetadata(req, res, next) {
next({
statusCode: 404,
message: "No metadata from the server; metadata is defined on the client"
});
}
I also read all document about Breeze/MongoDB but still doesn't help me to get Metadata for this.
The main point is I just want to change backend with BMEAN instead of WebAPI+EF+Breeze, don't need to change code on client.
Thanks
The metadata is provided by EF, not by MongoDB. If you are using a CodeFirst approach with EF then you should already have a DBContext.
This talks about how to use the DBContext -
http://www.breezejs.com/documentation/entity-framework-dbcontext
This talks about how to use EF as a design tool to build your meta data from classes -
http://www.breezejs.com/documentation/ef-design-tool
Odds are you already have what you need to generate the metadata it is just extending that and exposing a service to provide it to the client.
PW Kad's answer is correct, but to clarify, there is no way to get metadata from a MongoDB database because the database itself has an indeterminate structure. So you have to tell your client what the structure is. If you want to use the same client code for EF and Mongo then saving the metadata provided by the EFContext in your Mongo project makes a lot of sense. In other cases simply define the metadata directly on the client via Breeze's metadata api calls.

MEAN Stack: How to handle internationalization in front end error messages?

I am using a MEAN stack (mongodb, express, angular, nodejs) to develop an application. To render HTML in different languages I am using the i18n-2 node module.
But, I have some front end error messages (like validation errors - eg. Invalid Email). These messages appear based on user actions. How can these messages be internationalized?
One approach I can think of is to use hidden elements in jade / html and then pull out the same in angular / javascript. Alternatively, I can pass some ng-init variables in the jade file and then pull out the appropriate message at runtime in the angular controller.
Is the above approach ok? Or is there any other best practice for this?
Take a look at the Angular Translate module:
http://angular-translate.github.io/
Take a look at the Angular Auto Validate module:
http://jonsamwell.github.io/angular-auto-validate/
You could combine it with the Angular Translate module and create a custom error message resolver.

Resources