我在我公司的网站上有一个函数,它使用cgi.remote_host变量调用hostip.info提供的API 并返回orgin的国家/地区.这应该是这样的:
如果由于任何原因,我们无法将国家/地区与我们的某个地区相关联,我们会将用户重定向到默认网站.
什么实际发生的情况是,偶尔,我们的服务器无法定位API,我们得到一个超时错误.
这是我们要求获得领土的功能的代理:
<cffunction name="getGeoInfo" access="public" output="true" returntype="any" hint="call getGeoIP API and check country against DB">
<cfargument name="IPAddress" required="yes" type="string" />
<!--- Calling hostip API to get our Geo IP information --->
<cfhttp url="http://api.hostip.info/?ip=#arguments.IPAddress#" method="get" result="geoIP" />
<!--- Try to parse the file, if it can't parse, we don't create the variable --->
<cftry>
<cfset geoIPXML = xmlParse(geoIP.fileContent) />
<cfcatch type="any" />
</cftry>
<!--- If variable was created, perform the function to get territory info --->
<cfif isDefined("geoIPXML")>
<cfset countryAbbrev = geoIPXML.HostipLookupResultSet['gml:featureMember']['hostip']['countryabbrev'].xmlText />
<cfquery name="theTerritory" datasource="#request.dsource#">
SELECT territory
FROM countries
WHERE countryCode = <cfqueryparam value="#countryAbbrev#" cfsqltype="cf_sql_varchar" />
</cfquery>
<!--- If no record was found, set locale to default --->
<cfif theTerritory.recordcount EQ 0>
<cfset returnLocale = "default" />
<cfelse>
<!--- Otherwise set it to territory found in DB --->
<cfset returnLocale = theTerritory.territory />
</cfif>
<cfelse>
<!--- if no XML file was returned, set locale to default --->
<cfset returnLocale="default" />
</cfif>
<cfreturn returnLocale />
</cffunction>
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?我应该如何更改此功能,以便如果http请求超时,我仍然返回我的默认值?
包裹<cfhttp>呼叫<cftry>.
另外,我会让catch块只返回defaultLocale而不是什么都不做,然后检查是否存在geoIPXML.
<cftry>
<cfhttp url="http://api.hostip.info/?ip=#arguments.IPAddress#"
method="get"
result="geoIP"
throwOnError="yes" />
<cfset geoIPXML = xmlParse(geoIP.fileContent) />
<cfcatch type="any">
<cfreturn "default">
</cfcatch>
</cftry>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |