user1692342
user1692342

Reputation: 5237

Efficient way to handle error cases in REST Apis

I am writing a REST API in node.js. I expect at max 5 parameters to arrive in my GET Request. If there are unidentified parameters I wish to send 400 Bad Request. Currently I am handling it in the 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)
          {

             // do some processing
          }
          else {
             reply("No valid parameters").code(400);
           }
      }
});

Right now this does not handle the case if there are some valid and some invalid cases. I can solve that by using more if conditions. But I was just wondering if there is a standard or more efficient method which is used by developers

Upvotes: 1

Views: 1256

Answers (3)

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

Hapi has built-in validation support. You can use Joi to validate the 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 you send a request to /test?g=foo, then you get the following response:

{ statusCode: 400,
  error: 'Bad Request',
  message: '"g" is not allowed',
  validation: { source: 'query', keys: [ 'g' ] } }

Upvotes: 1

cmlndz
cmlndz

Reputation: 2357

Perhaps you should consider the use of a framework, like Express, to use a middleware which is simply code you can reuse in different routes.

A simple pseudo/example looks like this

var app = express();

// a middleware with no mount path; gets executed for every request to the app
app.use(function (req, res, next) {
  if (req.query.a && req.query.b) {
    return next()
  }
  else {
    return res.status(400).send('Not OK');
  }
});

// a route and its handler function (middleware system) which handles GET requests to /user/:id
app.get('/user/:id', function (req, res, next) {
  return res.send('OK');
});

// a different route, same middleware
app.get('/customer/:id', function (req, res, next) {
  return res.send('OK');
});

Upvotes: 0

BhavO
BhavO

Reputation: 2399

You can manually do this, but you are better off using a REST framework like mongoose or loopback (strongloop) to do the validation and error handling and other boilerplate code like model binding.

Upvotes: 0

Related Questions