Can you ask ruby to treat warnings as errors?

后端 未结 3 901
走了就别回头了
走了就别回头了 2020-12-01 11:03

Does ruby allow you to treat warnings as errors?

One reason I\'d like to do this is to ensure that if heckle removing a line of code means that a warning occurs, I h

相关标签:
3条回答
  • 2020-12-01 11:32

    You can finally do that by overriding Warning.warn like

    module Warning
      def warn(msg)
        raise msg
      end
    end
    

    This will turn the warning into an exception. This solution works at least since 2.4 branch.

    0 讨论(0)
  • 2020-12-01 11:42

    You could also potentially use DTrace, and intercept the calls to rb_warn and rb_warning, though that's not going to produce exceptions you can rescue from somewhere. Rather, it'll just put them somewhere you can easily log them.

    0 讨论(0)
  • 2020-12-01 11:50

    There is unfortunately no real way of doing this, at least not on most versions of Ruby out there (variations may exist), short of monitoring the program output and aborting it when a warning appears on standard error. Here's why:

    • Ruby defines Kernel.warn, which you can redefine to do whatever you wish (including exiting), and which you'd expect (hope) to be used consistently by Ruby to report warnings (including internal e.g. parsing warning), but
    • methods implemented natively (in C) inside Ruby will in turn directly invoke a native method called rb_warn from source/server.c, completely bypassing your redefinition of Kernel.warn (e.g. the "string literal in condition" warning, for example, issued when doing something like: do_something if 'string', is printed via the native rb_warn from source/parse.c)
    • to make things even worse, there is an additional, rb_warning native method, which can be used by Ruby to log warnings if -w or -v is specified.

    So, if you need to take action solely on warnings generated by your application code's calling Kernel.warn then simply redefine Kernel.warn. Otherwise, you have exactly two options:

    1. alter source/error.c to exit in rb_warn and rb_warning (and rb_warn_m?), and rebuild Ruby
    2. monitor your program's standard error output for ': warning:', and abort it on match
    0 讨论(0)
提交回复
热议问题