在vim / ruby​​中捕获错误

时间:2013-11-12 09:30:04

标签: ruby vim

我正在使用ruby界面编写vim插件。

当我执行VIM::command(...)时,如何检测vim在执行此命令期间是否引发错误,以便我可以跳过更多命令并向用户提供更好的消息?

1 个答案:

答案 0 :(得分:1)

Vim的全局变量v:errmsg将为您提供最后一个错误。如果要检查是否发生错误,可以先将其设置为空字符串,然后检查它:

let v:errmsg = ""

" issue your command

if v:errmsg != ""
  " handle the error
endif;

我将由您将其转移到Ruby API。另请参阅Vim内部的:h v:errmsg。其他有用的全局变量可能是:

  • v:exception
  • v:throwpoint

编辑 - 这应该有用(警告:涉及一些魔法):

module VIM
  class Error < StandardError; end

  class << self
    def command_with_error *args
      command('let v:errmsg=""')
      command(*args)
      msg = evaluate('v:errmsg')
      raise ::VIM::Error, msg unless msg.empty?
    end
  end
end


# Usage
# use sil[ent]! or the error will bubble up to Vim

begin
  VIM::command_with_error('sil! foobar') 
rescue VIM::Error => e
  puts 'Rescued from: ' + e.message;
end


# Output

Rescued from: E492: Not an editor command: sil! foobar