S. Caruso
S. Caruso

Reputation: 207

With loopback built-in methods, catch an error and return no error

I use Loopback 3. With my client-side application, I use the method POST User to create a new user. If the email adress already exists in basis, the server responds with an error of status 422. I would like to catch this error, so that the serveur returns no error.

I tried to use afterRemoteError like this :

User.afterRemoteError('create', function(context, next) {
  if (context.error && context.error.statusCode === 422
      && context.error.message.indexOf('Email already exists') !== -1
      && context.req.body && context.error.message.indexOf(context.req.body.email) !== -1) {
    context.error = null;
    next(null);
  } else {
    next();
  }
});

but this doesn't work, the server still returns the original error. If I try to replace the next(null) with a next(new Error('foo')) then the serveur returns the new error, but I didn't find how to return no error.

Upvotes: 0

Views: 322

Answers (1)

S. Caruso
S. Caruso

Reputation: 207

Tanks to my colleague that find the solution to the problem!

The fact is that afterRemoteError is triggered to late in the flow of the middlewares if we use next(). The solution is to self send the response with an express syntax:

User.afterRemoteError('create', function(context, next) {
    if (context.error && context.error.statusCode === 422
        && context.error.message.indexOf('Email already exists') !== -1
        && context.req.body && context.error.message.indexOf(context.req.body.email) !== -1)
    {
        context.res.status(200).json({foo: 'bar'});
    } else {
        next();
    }
});

Upvotes: 1

Related Questions