node.js - Efficient way to handle error cases in REST Apis -
i writing rest api in node.js. expect @ max 5 parameters arrive in request. if there unidentified parameters wish send 400 bad request. handling in following way:
server.route({ method: "get", path : "/test", handler : function (request, reply) { if (request.query.a || request.query.b || request.query.c || request.query.d || request.query.e) { // processing } else { reply("no valid parameters").code(400); } } }); right not handle case if there valid , invalid cases. can solve using more if conditions. wondering if there standard or more efficient method used developers
hapi has built-in validation support. can use joi validate query:
var joi = require('joi'); ... server.route({ method: 'get', path: '/test', config: { validate: { query: { a: joi.string(), b: joi.string(), c: joi.string(), d: joi.string(), e: joi.string() } } }, handler: function (request, reply) { return reply('ok'); } }); if send request /test?g=foo, following response:
{ statuscode: 400, error: 'bad request', message: '"g" not allowed', validation: { source: 'query', keys: [ 'g' ] } }
Comments
Post a Comment