I have read here that unhandled errors might cause cold starts. I am implementing a triggered function, as follows:
exports.detectPostLanguage = functions
.region("us-central1")
.runWith({ memory: "2GB", timeoutSeconds: "540" })
.firestore.document("posts/{userId}/userPosts/{postId}")
.onCreate(async (snap, context) => {
// ...
const language = await google.detectLanguage(post.text);
// ... more stuff if no error with the async operation
});
Do I need to catch the google.detectLanguage() method errors to avoid cold starts?
If yes, what should I do (A or B)?
A:
const language = await google.detectLanguage(post.text)
.catch(err => {
functions.logger.error(err);
throw err; // <---- Will still cause the cold start?
});
B:
try {
var language = await google.detectLanguage(post.text)
} catch(err) {
functions.logger.error(err);
return null; // <----
}
UPDATE
Based on Frank solution:
exports.detectPostLanguage = functions
.region("us-central1")
.runWith({ memory: "2GB", timeoutSeconds: "540" })
.firestore.document("posts/{userId}/userPosts/{postId}")
.onCreate(async (snap, context) => {
try {
// ...
const language = await google.detectLanguage(post.text);
// ... more stuff if no error with the async operation
} catch(err) {
return Promise.reject(err);
}
return null; // or return Promise.resolve();
});
CodePudding user response:
If any exception escapes from the Cloud Function body, the runtime assumes that the container is left in an unstable state and won't schedule it to handle events anymore.
To prevent this, ensure that no exception escapes from your code. You can either return no value, or a promise that indicates when any asynchronous calls in your code are done.