Jayson H
Jayson H

Reputation: 2048

FeathersJS - How to cancel hook on error

In my registration service I've created a 'before' hook to check if the user is already registered to a tournament. If the user is found to be registered, I have it throwing an error.

Per feathersjs documentation:

If a promise fails, the error will be propagated immediately and will exit out of the promise chain.

The problem I'm having is the error is being "triggered" and showing the user has already registered, but the registration still takes place. Meaning, the hook is never "exited".

Here is my function

exports.checkRegistered = () => {
    return (hook) => {
        let tourneyId = hook.data.tourneyId
        let userId = hook.data.userId

        return hook.service.find({
            query: {
                tourneyId: tourneyId,
                userId: userId
            }
        }).then(reg => {
            // User already registered
            if (reg.data.length != 0) {
              // Also tried to return a promise with same result.
              // return Promise.reject(new Error('Already registered.'))
              throw new Error('Already registered');
            }
        }).catch(err => {})
    }
}

Here is my "before hook" object

exports.before = {
  create: [
    api.checkRegistered()
  ]
};

Upvotes: 0

Views: 999

Answers (1)

Daff
Daff

Reputation: 44215

The problem is the .catch(err => {}). It will return a promise that just resolves successfully with undefined which will then continue the hook chain as if no error happened. Removing it should fix your issue.

Upvotes: 1

Related Questions