I am having an issue getting a 502 error back when I call my Netlify function. Is there something I am doing wrong in my Axios call or does the "error" sent in the callback need to be an actual Error object?
Below is the example of my function:
const axios = require('axios')
require('dotenv').config()
const https = require('https')
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type'
}
exports.handler = function (event, context, callback) {
// your server-side functionality
axios
.post(
`https://us18.api.mailchimp.com/3.0/lists/${
process.env.LIST_ID
}/members/`, {
email_address: '[email protected]',
status: 'subscribed'
}, {
auth: {
username: 'admin',
password: process.env.MAILCHIMP_API_KEY
}
}
)
.then(response => {
callback(null, {
statusCode: 200,
headers,
body: response.data
})
})
.catch(err => {
callback(JSON.stringify(err.response.data))
})
}
Netlify announced in April (2018) that Node.js 8.10 would be the default in Netlify functions.
When you need to return an error in Lambda functions on Netlify
using the Callback Parameter, it will be the same format as the Lambda functions for AWS.
You will need to return an Error in the first parameter of the callback
as you can see in the AWS documentation
callback(Error error, Object result);
The error
is used if not null and the result will be ignored.
You also have the option to return your error in the response with an error status code like the example function below.
import fetch from "node-fetch";
const API_ENDPOINT =
"https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke";
exports.handler = async (event, context) => {
return fetch(API_ENDPOINT)
.then(response => response.json())
.then(data => ({
statusCode: 200,
body: `${data.setup} ${data.punchline} *BA DUM TSSS*`
}))
.catch(error => ({ statusCode: 422, body: String(error) }));
};
exports.handler = function(event, context, callback) {
const err = new Error("this is an error")
callback(err);
}
Response (response status code 502):
{"errorMessage":"this is an error","errorType":"Error","stackTrace":["48.exports.handler (/var/task/showerror.js:75:13)"]}
exports.handler = function(event, context, callback) {
const err = {statusCode: 422, body: "this is an error"}
callback(err);
}
Response (response status code 502):
{"errorMessage":"[object Object]"}
exports.handler = function(event, context, callback) {
const err = "this is an error"
callback(err);
}
Response (response status code 502):
{"errorMessage":"this is an error"}
If you want to use callback and have the error status code in the response, you would just pass it in an object to the response.
exports.handler = function(event, context, callback) {
const err = {statusCode: 422, body: "this is an error"}
callback(null, err);
}
Response (response status code 422):
this is an error