0

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?

Finne
  • 150
  • 3
  • 8
  • The answer I gave should provide a generic way to deal with errors but can you also create an issue in https://github.com/feathersjs/feathers-sequelize/issues/new since I think it might be something worth changing in general. – Daff Mar 18 '17 at 20:42

1 Answers1

1

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: []
};
Daff
  • 43,734
  • 9
  • 106
  • 120
  • 1
    Thank you! I didn't realise that error hooks were implemented in the current version. For reference, I'm using the following to grab the error code: `hook.error.original.code, 'ER_BAD_FIELD_ERROR'` – Finne Mar 19 '17 at 14:28