Невозможно выдать ошибки в ApolloServer, необработанное отклонение обещания при отлове ошибки в Cognito - PullRequest
0 голосов
/ 30 декабря 2018

Создание моего первого распознавателя регистра пользователей для API GraphQL.

У меня проблемы с получением ответа об ошибке от Cognito API, когда я нажимаю его из распознавателя.

Журнал ошибок выглядит следующим образом и будет соответствовать приведенному ниже коду распознавателя.

{ data: { registerUser: null } }
error is here
{ code: 'UsernameExistsException',
  name: 'UsernameExistsException',
  message: 'An account with the given email already exists.' }
error is here
{ code: 'UsernameExistsException',
  name: 'UsernameExistsException',
  statusCode: 400,
  message: '400' }

Я удостоверился в следующем: - При поиске решателя из песочницы и клиента.- Я настроил ApolloServer для форматирования ответов и ошибок

КОД КОНФИГУРАЦИИ

const server = new ApolloServer({
typeDefs: [rootSchema, ...schemaTypes],
resolvers: merge({}, user),
async context({ req }) {
  const user = await authenticate(req)
  return { user }
},
formatResponse: response => {
        console.log(response);
        return response;
 },
formatError: error => ({
         message: error.message,
     state: error.originalError && error.originalError.state,
        locations: error.locations,
        path: error.path,
    })

});

const registerUser = (_, args, ctx) => {
var attributeList = [];
console.log('args')
console.log(args)

var params = {
    ClientId: "config.clientId",
    Password: args.user.password,
    Username: args.user.username,
    UserAttributes: attributeList
}
    userPool.signUp(args.user.email, args.user.password, attributeList, null, function(err, result){
        if (err) {
            console.log('error is here')
            console.log(err);
            throw new Error(err.message);
        }

        if(result) {
            console.log('result is here')
            console.log(result)
            cognitoUser = result.user;

        }

    }).catch(function(error) {
        console.log('error is below');
        console.log(error);
        return error;
    })

}

Две вещи мешаютя от продвижения вперед.Когда я опускаю блок catch из обещания userPool, я просто не получаю никакой ошибки, ошибка не генерируется изнутри функции signUp.

Если я выкидываю какую-либо ошибку из моего резольвера (будь то в обратном вызове или в блоке catch), я получаю следующую ошибку.

at process._tickCallback (internal/process/next_tick.js:160:7)
(node:28342) UnhandledPromiseRejectionWarning: Unhandled promise 
rejection. This error originated either by throwing inside of an async 
function without a catch block, or by rejecting a promise which was not 
handled with .catch(). (rejection id: 1)
(node:28342) [DEP0018] DeprecationWarning: Unhandled promise rejections 
are deprecated. In the future, promise rejections that are not handled 
will terminate the Node.js process with a non-zero exit code.

Я хотел бы получить следующую ошибку, которая будет возвращена в Песочницу / Запросчик

{ data: { registerUser: null } }
error is here
{ code: 'UsernameExistsException',
  name: 'UsernameExistsException',
  message: 'An account with the given email already exists.' }

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 31 декабря 2018

Разобрался.API-интерфейсы AWS ограничены реализацией Callback.Оберните свой обратный вызов как обещание - затем цепочку, которую обещание бросают по мере необходимости.

...