要解决这个问题,你可以使用try-catch块来处理可能发生的异常。下面是一个使用Apps Script的Calendar服务的示例代码,演示了如何使用getEventById()方法并处理可能返回null的情况:
function getEventByIdExample() {
var calendarId = 'your-calendar-id';
var eventId = 'your-event-id';
try {
var event = CalendarApp.getCalendarById(calendarId).getEventById(eventId);
if (event) {
// 找到了具有指定id的事件
Logger.log('Event title: ' + event.getTitle());
} else {
// 没有找到具有指定id的事件
Logger.log('Event not found');
}
} catch (error) {
// 处理异常
Logger.log('An error occurred: ' + error);
}
}
在上述代码中,我们将calendarId和eventId替换为你自己的日历ID和事件ID。然后,我们使用try-catch块来捕获可能发生的异常。如果getEventById()方法返回null,我们将在日志中打印"Event not found"。如果发生其他异常,我们将打印错误消息。
请注意,你需要在执行此代码之前在你的项目中启用Calendar服务。你可以通过在脚本编辑器中选择“资源”>“高级Google服务”并启用Calendar服务来实现这一点。