I'm running a AWS Lambda function in Node.js 14, bound to a REST API in API Gateway with LAMBDA_PROXY.
Consider this simplified Pseudo Code for index.js:
exports.handler = async function (event, context) {
if (event.body.myParam === '1') {
// Works!
return {
statusCode: 302,
headers: {
Location: 'https://iam.aredire.ct'
}
};
} else if (event.body.myParam === '2') {
// Works! 403 - {"message":"You are not allowed to do that!"}
return {
statusCode: 403,
body: JSON.stringify({
message: 'You are not allowed to do that!'
})
};
} else if (event.body.myParam === '3') {
const jwt = require('jsonwebtoken');
const token = 'ey...';
const pubKey = '-----BEGIN PUBLIC KEY----- ...';
// Some promise
return new Promise(function (resolve, reject) {
// Some async call
jwt.verify(token, pubKey, function (err, decoded) {
if (err) {
// gets logged
console.log(err);
// 502 - {"message": "Internal server error"}
return reject({
statusCode: 403,
body: JSON.stringify({
message: 'No valid token'
})
});
// 502 - {"message": "Internal server error"}
return reject(JSON.stringify({
statusCode: 403,
body: {
message: 'No valid token'
}
}));
}
// Works! 200 - {"message":"Works!"}
resolve({
statusCode: 200,
body: JSON.stringify({
message: 'Works!'
})
});
});
});
}
}
Please see the comments in the code snippets. Do you have any idea why resolve() and return work as expected but reject() always returns 502 - {"message": "Internal server error"}? I want that the requester actually gets a 403 - {"message": "No valid token"}?
I read about JSON.stringifying the whole error object, but that does not help.
Cloudwatch raises this error:
ERROR Invoke Error
{
"errorType": "Error",
"errorMessage": "{\"statusCode\":403,\"body\":{\"message\":\"No valid token\"}}",
"stack": [
...
]
}