Google Directions API随机返回UNKNOWN_ERROR的调试求助
UNKNOWN_ERROR Responses from Google Directions API 我太懂这种随机UNKNOWN_ERROR的烦人程度了——没规律、没详细报错,控制台只给个计数,完全摸不着头脑。结合你贴的代码,我整理了几个实打实的调试方向,一步步来排查:
给请求加详细日志,抓错误现场
随机错误往往和特定请求参数有关,你得把每次请求的完整参数都记录下来,尤其是错误发生时的参数。在调用directionsService.route前加一段日志代码:// 打印完整请求参数,方便错误回溯 console.log('Directions API Request Details:', JSON.stringify({ origin: { lat: origin.lat(), lng: origin.lng() }, waypoints: waypoints.map(w => ({ lat: w.location.lat(), lng: w.location.lng(), stopover: w.stopover })), destination: { lat: destination.lat(), lng: destination.lng() }, travelMode: routeData.travelMode, optimizeWaypoints: routeData.optimizeWaypoints }));这样下次错误出现时,你就能拿到当时的经纬度、路径点等信息,说不定能发现规律——比如是不是某些偏远地区的坐标触发的,或者高峰期请求才会出问题。
加重试机制,应对临时服务波动
UNKNOWN_ERROR很多时候是Google服务端的临时抽风,给失败请求加几次重试能解决大部分这类问题。修改你的请求逻辑,比如:const MAX_RETRIES = 3; let retryCount = 0; function getRoute(routeParams) { directionsService.route(routeParams, (response, status) => { if (status === google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } else if (status === google.maps.DirectionsStatus.UNKNOWN_ERROR && retryCount < MAX_RETRIES) { retryCount++; console.log(`Retry ${retryCount}/${MAX_RETRIES} for UNKNOWN_ERROR`); // 用递增间隔避免频繁请求 setTimeout(() => getRoute(routeParams), retryCount * 1000); } else { console.error('Failed after retries. Status:', status, 'Request:', routeParams); // 这里可以把错误上报到你的日志系统,方便后续分析 } }); } // 初始调用 getRoute(routeData);这样既减少了临时错误导致的业务失败,还能在最终失败时把关键信息存下来。
检查API配额和请求频率
虽然官方说配额超限会返回OVER_QUERY_LIMIT,但偶尔也会以UNKNOWN_ERROR的形式出现。去Google API控制台看看Directions API的配额使用情况:- 确认是不是高峰期接近配额上限
- 检查请求频率是不是太高,有没有触发限流
如果是配额问题,要么调整请求频率,要么申请提高配额。
验证参数合法性,排除隐性错误
你的代码结构没问题,但偶尔可能出现经纬度值异常(比如NaN、超出[-90,90]/[-180,180]范围)。在构造LatLng前加个验证:function isLatLngValid(lat, lng) { return !isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180; } // 验证起点 if (!isLatLngValid(latitude1, longitude1)) { console.error('Invalid origin coordinates:', latitude1, longitude1); return; } // 对终点和途经点做同样验证避免因为参数不合法导致的隐性错误被包装成
UNKNOWN_ERROR。用Cloud Logging挖深层错误细节
别只看API控制台的错误计数,Google Cloud Logging里有更详细的请求日志:- 打开Google Cloud Console,进入你的项目
- 搜索进入「Cloud Logging」
- 用过滤器
resource.type="api" AND service="directions.googleapis.com"筛选日志
这里能看到每一次请求的完整详情,包括服务端返回的具体错误信息(哪怕是UNKNOWN_ERROR,也可能有内部超时、资源不足等细节)。
按这些步骤走,应该能逐步定位到随机错误的根源。
内容的提问来源于stack exchange,提问作者Seltix

