【问题标题】:Is there any way to recover from Psych::SyntaxError?有没有办法从 Psych::SyntaxError 中恢复?
【发布时间】:2013-08-22 19:38:05
【问题描述】:

当 i18n 语言环境 YAML 文件中存在语法错误时,会引发 Psych::SyntaxError。如果在 Rails 启动期间遇到此异常(例如,重新启动生产时),Rails 会崩溃。

  1. 有什么方法可以捕获此异常并以某种方式从中恢复,而不会使 Rails 完全崩溃?
  2. 有没有办法在提交或部署之前以自动方式检查语言环境文件的语法错误?

【问题讨论】:

    标签: ruby ruby-on-rails-3 internationalization yaml


    【解决方案1】:

    我不确定是否有办法从这个错误中恢复,但我创建了一个 rake 任务,以确保给定的 YAML 文件在语法上是有效的(通过预提交 git 挂钩运行任何更改的 YAML 文件):

    namespace :yaml do
      desc "Check YAML syntax for errors."
      task :check_syntax do
        require 'YAML'
        require 'colorize'
    
        puts "Checking YAML files..."
    
        filenames = (ENV['FILENAMES'].split(',') || []).push(ENV['FILENAME']).uniq.compact
        fails = 0
    
        filenames.each do |file|
          print "#{file}... "
    
          begin
            YAML.load_file(file)
          rescue Psych::SyntaxError => e
            fails += 1
            print "Failed! ".red
            print "[#{e.message.sub(/\A.*: /, '')}]"
            puts
            next
          end
    
          print "Success!".green
          puts
        end
    
        puts
    
        exit fails > 0 ? 1 : 0
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2011-10-31
      • 2016-04-05
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多