问题
I'm writing a Gmail Addon with Appscript. If the application throws an unhandled error, it will be automatically logged on stackdriver and displayed in Stackdriver Error Reporting. However, I want to manually send errors to Stackdriver Error Reporting:
try{
thisMayThrowAnError();
catch(err){
console.error(new Error("Something Failed"))
}
In the example above, the error log is being displayed in Stackdriver Logs, but it won't appear on Stackdriver Error Reporting. Is there a way to achieve this without actually throwing it (and crashing the addon)?
回答1:
- You want to manually report a custom error to StackDriver Error Reporting.
- You don't want to stop the script.
If my understanding is correct, how about this workaround? In this workaround, it uses the method of projects.events.report
in Stackdriver Error Reporting API.
Before you use this sample script, please do the following operations.
- Add
https://www.googleapis.com/auth/cloud-platform
to the scopes using Manifests and others. - Enable Stackdriver Error Reporting API at API console.
Sample script:
try {
thisMayThrowAnError();
} catch(err) {
var projectId = "project-id-#####"; // Please set the project ID of project including your script.
var payload = { // Please modify this for your situation.
message: "Something Failed",
serviceContext: {service: "sample"},
context: {reportLocation: {functionName: "sampleFunctionName"}},
};
var url = "https://clouderrorreporting.googleapis.com/v1beta1/projects/" + projectId + "/events:report";
var params = {
method: "post",
payload: JSON.stringify(payload),
contentType: "application/json",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
}
UrlFetchApp.fetch(url, params);
}
Note:
- This is a simple sample script. So please modify to your situation.
- In this script, each value of
payload
is sample values. So please modify to your situation. - When I called this API, there was the case that the reflection of result is late. So if the result is not reflected to StackDriver Error Reporting after you called the API, please wait a moment.
References:
- Stackdriver Error Reporting API
- projects.events.report
- ErrorContext
- ServiceContext
- Identifying projects
From your question, I understood that you are using Google Apps Script. If you are using other language, please tell me. If this workaround was not the result you want, I apologize.
来源:https://stackoverflow.com/questions/54093641/appscript-handled-errors-not-shown-in-stackdriver-errors