Search code examples
feathersjsfeathers-sequelize

Catch invalid request & return error with feathers-sequelize


I am new to feathers and am building an API, generated with feathers-cli. If the client performs an invalid GET request:

eg. http://localhost:3030/stations/?asdfasdf

it returns a 500 error:

ER_BAD_FIELD_ERROR: Unknown column 'stations.asdfasdf' in 'where clause'

I'd rather not report an error like that back to the client and would instead like to return a '400 Bad Request' instead. I've tried setting up an after hook using hook.error but this doesn't catch the sequelize error.

How can I catch the error and return a safer, more generic message to the client?


Solution

  • error hooks are a separate new hook type. With the 1.x feathers-cli change your services index file from something like

    // Set up our before hooks
    messageService.before(hooks.before);
    
    // Set up our after hooks
    messageService.after(hooks.after);
    

    To

    // Set up hooks
    messageService.hooks(hooks);
    

    Then in the hooks/index.js file add

    exports.error = {
      all: [],
      find: [],
      get: [],
      create: [],
      update: [],
      patch: [],
      remove: []
    };
    

    You can now use it to create error hooks. For your case like this:

    const errors = require('feathers-errors');

    exports.error = {
      all: [
        function(hook) {
          if(is(hook.error, 'ER_BAD_FIELD_ERROR')) { // Somehow check the Sequelize error type
            hook.error = new errors.BadRequest('Invalid query field');
          }
        }
      ],
      find: [],
      get: [],
      create: [],
      update: [],
      patch: [],
      remove: []
    };