53

Let's say I have a rakefile like this:

file 'file1' => some_dependencies do
  sh 'external tool I do not have control over, which sometimes fail to create the file'
  ???
end

task :default => 'file1' do
  puts "everything's OK"
end

Now if I put nothing in place of ???, I get the OK message, even if the external tool fails to generate file. What is the proper way to informing rake, that 'file1' task has failed and it should abort (hopefully presenting a meaningful message - like which task did fail) - the only think I can think of now is raising an exception there, but that just doesn't seem right.

P.S The tool always returns 0 as exit code.

dahpgjgamgan
  • 2,977
  • 4
  • 25
  • 26

2 Answers2

63

Use the raise or fail method as you would for any other Ruby script (fail is an alias for raise). This method takes a string or exception as an argument which is used as the error message displayed at termination of the script. This will also cause the script to return the value 1 to the calling shell. It is documented here and other places.

Richard Cook
  • 32,523
  • 5
  • 46
  • 71
  • 5
    [`fail`](http://ruby-doc.org/core-2.0/Kernel.html#method-i-fail) is just an alias for [`raise`](http://ruby-doc.org/core-2.0/Kernel.html#method-i-raise) – Stefan Jul 23 '13 at 21:18
  • Right you are. Updated my answer to indicate this. – Richard Cook Jul 28 '13 at 04:42
  • @Dan Tenenbaum: Thanks. Replaced with a working link. – Richard Cook Sep 14 '14 at 19:04
  • 1
    Although similar to `abort`, the latter seems to be more appropriate in this case. `fail` displays a stack trace (not user-friendly output). And raises a `RuntimeError`, which hints that you might want to catch it (since `rescue` defaults to `StandardError` and descendants, to which `RuntimeError` belongs, and to which `SystemExit` doesn't). – x-yuri Oct 19 '21 at 06:31
29

You can use abort("message") to gracefully fail rake task.

It will print message to stdout and exit with code 1.

Exit code 1 is a failure in Unix-like systems.

See Kernel#abort for details.

Senid
  • 563
  • 5
  • 13