You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Places API如何监听错误事件?

Google Places Autocomplete 错误捕获(含速率限制)

Google Places Autocomplete 组件本身没有提供专门的错误事件供直接订阅,但可以通过以下几种方式捕获速率限制等错误,实现优雅处理:

1. 监听全局 Google Maps 错误事件

Google Maps JavaScript 库会在全局抛出错误事件,你可以监听 window 对象的 error 事件来捕获包括速率限制(状态码 429)在内的所有 Maps 相关错误:

google.maps.event.addListener(window, 'error', function(e) {
  if (e.error?.code === 429) {
    // 处理速率限制错误,向用户展示提示
    alert('请求过于频繁,请稍后再尝试');
  } else {
    // 处理其他 Google Maps 相关错误
    console.error('Google Maps 错误:', e.error);
  }
});

2. 校验 getPlace() 返回结果

当 place_changed 事件触发后,若调用 getPlace() 返回的对象缺少 place_id、formatted_address 等核心字段,大概率是请求失败(比如触发速率限制),可以据此做错误处理:

const place = new google.maps.places.Autocomplete(inputRef.value, options);
google.maps.event.addListener(place, 'place_changed', function () {
  const placeDetails = place.getPlace();
  if (!placeDetails.place_id) {
    // 提示用户地址获取失败
    alert('无法获取地址信息,请稍后再试');
    return;
  }
  // 正常处理逻辑
  const { place_id: placeIdGoogle, formatted_address: name } = placeDetails;
  // ...
});

补充说明

速率限制错误通常是因为短时间内请求次数超过了 API 配额,除了前端提示用户,也建议优化前端请求逻辑(比如增加输入防抖,减少不必要的自动补全请求),同时在后端做好配额监控。

内容的提问来源于stack exchange,提问作者thisismydesign

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:40:08