I am not certain whether the ability to retry a code block when encountering exceptions was a feature available in Ruby, but I certainly couldn’t find anything on that topic (what I did find were mostly about the retry keyword for iterator loops).
Before you ask why I need this, the motivation for this was because I was getting intermittent HTTP errors (503s mostly) trying to connect to a web service. Turns out it’s really easy in Ruby to implement a retryable method that does something like this:
retryable(:tries => 5, :on => OpenURI::HTTPError) do
open('http://example.com/flaky_api')
# Code that mashes up stuff for your "social networking" site.
end
Here are the Kernel#retryable specs (pastie).
And the code:
# Options:
# * :tries - Number of retries to perform. Defaults to 1.
# * :on - The Exception on which a retry will be performed. Defaults to Exception, which retries on any Exception.
#
# Example
# =======
# retryable(:tries => 1, :on => OpenURI::HTTPError) do
# # your code here
# end
#
def retryable(options = {}, &block)
opts = { :tries => 1, :on => Exception }.merge(options)
retry_exception, retries = opts[:on], opts[:tries]
begin
return yield
rescue retry_exception
retry if (retries -= 1) > 0
end
yield
end
It’s not hard to implement the same for checking return values as well, i.e.
retryable_deluxe(:tries => 5, :on => { :return => nil }) { puts "working..." }
retryable_deluxe(:on => { :exception => StandardError, :return => nil }) do
# your code here
end
Ruby is nice.
分享到:
相关推荐
在Ruby中,错误处理主要通过异常(Exception)机制,使用begin...rescue...end块来捕获和处理可能出现的问题。这有助于编写健壮的代码,确保程序在遇到错误时能正常运行。 Ruby的元编程能力是其独特之处,允许在...
- 控制结构:包括条件语句(`if/else`,`unless`,`case`),循环(`for`,`while`,`until`,`each`)和流程控制(`break`,`next`,`redo`,`retry`)。 2. **面向对象编程(OOP)** - 类与对象:Ruby是纯面向...
少儿编程scratch项目源代码文件案例素材-纸人伙计.zip
scratch少儿编程逻辑思维游戏源码-忍者罗伊 V5.zip
scratch少儿编程逻辑思维游戏源码-跑和枪.zip
前端开发_基于jQuery和EasyUI框架_企业级Web应用UI组件库与后台管理系统模板_提供GPL开源版本和商业授权版本的双重授权模式_适用于快速构建响应式管理后台和复杂数据可
少儿编程scratch项目源代码文件案例素材-纸格通关 云变量.zip
微信机器人开发_Wechaty框架_百度云主机部署_自然语言处理_消息自动化处理_多媒体文件管理_聊天记录持久化_表情包导出_语音视频自动保存_文件管理系统集成_跨平台数据同步_个
少儿编程scratch项目源代码文件案例素材-钻机机器人.zip
少儿编程scratch项目源代码文件案例素材-作战基地.zip
云计算_微服务分布式架构SpringCloudSpringBootDubboVuejs_互联网云快速开发框架敏捷开发系统代码生成工作流CMS图表统计地图统计_免费开源JAVA企业
scratch少儿编程逻辑思维游戏源码-日落塔.zip
Tobapuww_GPT-Recovery-Files_12888_1745866661386
少儿编程scratch项目源代码文件案例素材-战斗竞技场.zip
scratch少儿编程逻辑思维游戏源码-球球大作战.zip
聚合支付系统/官方个人免签系统/三方支付系统稳定安全高并发 附教程 系统采用FastAdmin框架独立全新开发,安全稳定,系统支持代理、商户、码商等业务逻辑。 针对最近一些JD,TB等业务定制,子账号业务逻辑API 非常详细,方便内置对接! IP白名单 业务逻辑 支持IP白名单,黑名单,全局白名单,全局黑名单,保障系统的安全。 接口验签名 采用支付宝RSA加密接口方式,防止篡改数据,导致对账困难,资金大量损失,无故少钱 对接灵活 全部对接参数灵活操作 风控完善 轮询、交易金额、随机金额、最大金额、最小金额等 测试环境: Nginx+PHP7.0+MySQL5.6 网站运行目录:/public 伪静态设置为:thinkphp规则 数据库信息修改路径:/application/database.php
校园社交服务_微信小程序云开发_公告资讯失物招领二手交易兼职招聘表白墙_为高校师生提供一站式校园生活服务平台包含校园动态通知课程表查询失物发布与认领二手物品交易平台兼职信息发布与求
yinghuayu2377_myFTPDemo_32152_1745866651913
scratch少儿编程逻辑思维游戏源码-魔法球.zip
idea导入个人风格