'Trying to call an external api with aws lamda returning error type object
This is my code in which i am trying to call an external api with aws lambda.
const http = require('http');
exports.handler = async (event) => {
let dataString = '';
const options = {
host: 'host',
path: '/v1/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
const response = await new Promise((resolve, reject) => {
const req = http.request(options, function(res) {
res.on('data', chunk => {
dataString += chunk;
});
res.on('end', () => {
resolve({
statusCode: 200,
body: JSON.stringify(JSON.parse(dataString), null, 4)
});
});
});
req.on('error', (e) => {
reject({
statusCode: 500,
body: 'Something went wrong!'
});
});
});
return JSON.stringify(response);
};
But what I am getting in response is as follows.
Test Event Name test1
Response { "errorType": "object", "errorMessage": "[object Object]", "trace": [] }
Function Logs START RequestId: c9701afa-9bc5-4750-8e10-5558d5e3e342 Version: $LATEST 2022-03-03T07:23:07.844Z c9701afa-9bc5-4750-8e10-5558d5e3e342 ERROR Invoke Error {"errorType":"Error","errorMessage":"[object Object]","stack":["Error: [object Object]"," at _homogeneousError (/var/runtime/CallbackContext.js:12:12)"," at postError (/var/runtime/CallbackContext.js:29:54)"," at done (/var/runtime/CallbackContext.js:58:7)"," at fail (/var/runtime/CallbackContext.js:70:7)"," at /var/runtime/CallbackContext.js:106:16"," at processTicksAndRejections (internal/process/task_queues.js:95:5)"]} END RequestId: c9701afa-9bc5-4750-8e10-5558d5e3e342 REPORT RequestId: c9701afa-9bc5-4750-8e10-5558d5e3e342 Duration: 198.36 ms Billed Duration: 199 ms Memory Size: 128 MB Max Memory Used: 57 MB Init Duration: 156.11 ms
Request ID c9701afa-9bc5-4750-8e10-5558d5e3e342
How do i debug this?
Solution 1:[1]
Pass your "reject" error object to JSON.stringify and the nested error message object will be readable instead of just being [object Object] in the response.
I also suggest passing the actual error object along in the body, so that you can see from the response what has gone wrong:
req.on('error', (e) => {
reject(JSON.stringify({
statusCode: 500,
body: 'Something went wrong: ' + e
}));
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eli6 |
