如何捕获ruby中的所有异常?

Gar*_*Dan 5 ruby exception-handling exception

我们如何捕获或/和处理ruby中所有未处理的异常?

例如,这样做的动机可能是将不同的文件记录到不同的文件或发送和发送电子邮件到系统管理.

在Java中我们会这样做

Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ex);
Run Code Online (Sandbox Code Playgroud)

在NodeJS中

process.on('uncaughtException', function(error) {
   /*code*/
});
Run Code Online (Sandbox Code Playgroud)

在PHP中

register_shutdown_function('errorHandler');

function errorHandler() { 
    $error = error_get_last();
    /*code*/    
}
Run Code Online (Sandbox Code Playgroud)

我们怎么能用红宝石做到这一点?

小智 8

高级解决方案使用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
Run Code Online (Sandbox Code Playgroud)

您可以在此主题中找到更多详细信息.


小智 3

在 Ruby 中,您只需将程序包装在begin//块中。任何未处理的异常都会冒泡到该块并在那里进行处理。rescueend