I have the code below, where I first use AJV to validate a json schema and if it is valid it just prints a message in the log, if not it should call axios to send a notification to slack:
import Ajv from "ajv";
import { inspect } from "util";
const ajv = new Ajv({ allErrors: true });
import axios, * as others from 'axios';
export const validatorFactory = (schema) => {
const validate = ajv.compile(schema);
const verify = (data,valueObj,MessageId) => {
const isValid = validate(data);
if (isValid) {
console.log ("Validação foi feita com sucesso, a mensagem recebida está de acordo com o contrato!");
return data;
}else{
data = JSON.stringify(data);
console.log ("Validação do contrato falhou: " + data);
let config = {
headers: {
"Content-Type": "application/json",
'Accept-Encoding': 'application/json'
}
};
var validateError = validate.errors;
validateError = JSON.stringify(validateError);
const reqBody = JSON.stringify({
"reportType": valueObj,
"messageId": MessageId,
"bodyMessage": data,
"Error": validateError
});
axios.post('https://hooks.slack.com/triggers/{endpoint}', reqBody,config).then(function (response) {
console.info(`Message posted successfully: ${JSON.stringify(response)}`);
}).catch((error) => {
if( error.response ){
console.error("Post para canal do Slack falhou. Status code: " + error.response.status);
console.log(error.response.data); // => the response payload
}
});
}
};
return { schema, verify };
};
The problem is that it doesn’t send or log an error in the catch I placed. It doesn’t actually print anything. Calling the url through postman sends it and the crazy thing is that if I add:
throw new Error(
ajv.errorsText(
validate.errors?.filter((err) => err.keyword !== "if"),
{ dataVar: "schemaValidation" } + "nn" + inspect(data)
)
);
It works.
But I don’t want the lambda to throw an error, because if it throws my message (with an error in the contract) it will go back to the sqs queue and be reprocessed and then there will be several notifications in a row in slack, for the same message.
I just want that, if an error occurred in the contract, the warning message is sent, but the flow ends successfully and it is removed from the queue.
I can’t understand why I need a “Throw Error” for the message to be sent to slack