Ниже представлена облачная функция, которая берет данные и добавляет их в две коллекции в моей базе данных. Этот код возвращает «Необработанное исключение» 4/10 раз. Он работает большую часть времени, но случайным образом возвращает эту ошибку. Мне не удалось отследить, где это происходит, потому что, если я попробую еще раз, это сработает.
exports.addSafe = functions.https.onCall((data, context) => {
// The HTTP endpoint is going to receive an object with an attribute "data", which is going to contain an array of objects with every single safe data point to add
let validated = true;
if (validated === false) {
console.log('Data cannot be validated. Misses the correct attributes')
} else {
for (let i=0; i<data.length; i++) {
try
{
//Checking if safe with the given MAC already exists in the collection Safes-Hardware
// eslint-disable-next-line no-await-in-loop
var ifPresent = db.collection("Safes-Hardware").doc(data[i]['Mac address Check']);
ifPresent.get()
.then(async (doc)=>{
if (!doc.exists)
{
console.log("Document does not exit. Proceeding to add if MAC adddress is valid");
//Validating MAC Address
var regEx = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
var validFormat =regEx.test(data[i]['Mac address Check']);
if (validFormat){
console.log('Mac address - Validated');
try{
//Main Collection with the parsed data
// eslint-disable-next-line no-await-in-loop
const docRef = await db.collection('Safes').add(data[i])
console.log('Mac written with ID: ', docRef.id);
try{
//Lookup Collection being populated
// eslint-disable-next-line no-await-in-loop
await db.collection('Safes-Hardware').doc(data[i]['Mac address Check'])
.set({
ID : docRef.id
})
console.log("Reference added");
}
catch(err){
console.log("Error while adding reference",err)
}
}
catch(err){
console.log("Error while adding data to 'Safe' collection",data[i])
}
}
else{
console.log("MAC Address invalid", data[i]['Mac address Check'])
}
}
else
{
console.log("Document exists in database. Skipping safe with MAC Address: ",data[i]['Mac address Check']);
}
return { message: "Success is within the palm of our hands." }
})
.catch((error)=>{
console.log("Error while checking for duplicates", error);
});
}
catch(error){
console.log("Error logged",error)
}
}
}
})
Облачная функция вызывается здесь:
handleUpload = async (event) => {
event.preventDefault();
let data = this.state.file.data;
// let uploadedFile = this.state.file;
console.log('Data variable before file upload', data);
if (data && data.length > 0) {
const firstSafeObject = data[0];
fileValidated = true
if (fileValidated === true) { /
let dataObj = { // so that it theoretically goes through every time. There's another layer of validation on the backend so even then, a random
"data": data // file that does not contain the necessary attributes will not go through. Go ahead and try :)
}
try {
console.log(dataObj)
const addedDataResults = await axios.post(
'https://us-central1-silo-c8eef.cloudfunctions.net/addSafe', // TOCHANGE: You should probably make this an environment variable
dataObj
)
console.log('Data added to DB successfully');
console.log('Data', addedDataResults)
// Changes the state to activate success message for user
//Storing the uploaded file on firebase storage
let bucketName = "Files"
let fileToUpload = this.state.originalFile
let storageRef = firebase.storage().ref(`${bucketName}/${fileToUpload.name}`)
let uploadTask = storageRef.put(fileToUpload)
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
()=>{
let downloadURL = uploadTask.snapshot.downloadURL
console.log('File uploaded to added to Storage successfully at location: ',downloadURL);
console.log('File', fileToUpload)
})
var user = firebase.auth().currentUser;
if (user) {
console.log("Current user is: ",user.email)
let fileDetails = [fileToUpload.name, user.email]
console.log(fileDetails)
let fileObj = { //Attriubutes for file-details collection
"data": fileDetails
}
try{
await axios.post('https://us-central1-silo-c8eef.cloudfunctions.net/addFileDetails',
fileObj)
}
catch(error) {
console.log('File details not added to Firebase DB successfully',error)
alert('File details could not be added')
}
} else {
console.log("No user currently logged in ")
alert('LOG IN FIRST!')
}
this.setState({
successfullyUploaded: true,
inputKey: Date.now(),
})
// Clears out the input to prevent the file from being mistakenly uploaded twice
} catch(error) {
console.log('Data not added to Firebase DB successfully')
alert('Data not added to DB. Make sure the CSV file is correct.')
}
} else {
alert('File is not a safe file or data format incorrect. Please upload safe file with the correct properties.');
}
}
}
Ошибка I ' m входит (журнал функции addSafe Cloud):
addSafe
Unhandled rejection
FetchError: request to https://www.googleapis.com/oauth2/v4/token failed, reason: socket hang up at ClientRequest.<anonymous> (/srv/node_modules/node-fetch/lib/index.js:1455:11) at emitOne (events.js:116:13) at ClientRequest.emit (events.js:211:7) at TLSSocket.socketErrorListener (_http_client.js:401:9) at emitOne (events.js:116:13) at TLSSocket.emit (events.js:211:7) at emitErrorNT (internal/streams/destroy.js:66:8) at _combinedTickCallback (internal/process/next_tick.js:139:11) at process._tickDomainCallback (internal/process/next_tick.js:219:9)
Will this be some problem on the server-side?
Я нашел это в Интернете: https://github.com/firebase/firebase-admin-node/issues/540 Здесь они сказали, что перезапуск сервера решает проблему, и это правда, но я не могу позволить себе каждый раз перезагружать сервер? Мне не хватает catch () или вы, ребята, видите, где я не обрабатываю ошибку?