如何捕获rails中的错误?

时间:2012-12-06 13:37:24

标签: ruby-on-rails ruby-on-rails-3 heroku

我在heroku中有一个rails应用程序。这些值将传递给服务器,并且它可以正常工作,有时会显示错误,如

<!DOCTYPE html> <html> <head>   <title>We're sorry, but something went wrong (500)</title>   <style type="text/css">
    body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
    div.dialog {
      width: 25em;
      padding: 0 4em;
      margin: 4em auto 0 auto;
      border: 1px solid #ccc;
      border-right-color: #999;
      border-bottom-color: #999;
    }
    h1 { font-size: 100%; color: #f00; line-height: 1.5em; }   </style> </head>

<body>   <!-- This file lives in public/500.html -->   <div class="dialog">
    <h1>We're sorry, but something went wrong.</h1>
    <p>We've been notified about this issue and we'll take a look at it shortly.</p>   </div> </body> </html>

所以我不希望这样的错误。相反,我希望得到这些错误,并在json中向应用程序显示unexpected error之类的内容。我怎样才能做到这一点?请帮帮我。

1 个答案:

答案 0 :(得分:2)

在application_controller.rb

中添加以下代码
rescue_from "ActiveRecord::RecordNotFound" do |exception|
   render :json => {:error => 'page not found' }
end

同样,您可以在rescue_from方法

中添加所需的所有例外
rescue_from "Exception" do |exception|
 render :json => {:error => 'Unexpected error occurred' }
end