我们如何捕获或/和处理ruby中所有未处理的异常?
这样做的动机可能是将不同文件的某些异常记录下来,或者发送电子邮件给系统管理员。例如。
在Java中我们会做
Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ex);
在NodeJS中
process.on('uncaughtException', function(error) {
/*code*/
});
在PHP中
register_shutdown_function('errorHandler');
function errorHandler() {
$error = error_get_last();
/*code*/
}
我们如何用ruby做到这一点?
答案 0 :(得分:7)
高级解决方案使用exception_handler gem
如果您只想捕获所有异常并将其放在日志中,可以将以下代码添加到ApplicationController
:
begin
# do something dodgy
rescue ActiveRecord::RecordNotFound
# handle not found error
rescue ActiveRecord::ActiveRecordError
# handle other ActiveRecord errors
rescue # StandardError
# handle most other errors
rescue Exception
# handle everything else
end
您可以在此thread中找到更多详细信息。
答案 1 :(得分:3)
在Ruby中,您只需将程序包裹在begin
/ rescue
/ end
块中。任何未处理的异常都将冒泡到该块并在那里处理。