1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Exit A Process With An Error Message as a Ruby til

This commit is contained in:
jbranchaud
2022-05-09 09:40:55 -05:00
parent 2ac7486fbe
commit 4efc312b90
2 changed files with 36 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1194 TILs and counting..._
_1195 TILs and counting..._
---
@@ -948,6 +948,7 @@ _1194 TILs and counting..._
- [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md)
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
- [Exclude Values From An Array](ruby/exclude-values-from-an-array.md)
- [Exit A Process With An Error Message](ruby/exit-a-process-with-an-error-message.md)
- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md)
- [Extract A Column Of Data From A CSV File](ruby/extract-a-column-of-data-from-a-csv-file.md)
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)

View File

@@ -0,0 +1,34 @@
# Exit A Process With An Error Message
If you want to exit a Ruby process with an unsuccessful error code like `1`,
you can use
[`Kernel.exit`](https://ruby-doc.org/core-3.1.2/Kernel.html#method-i-exit).
```ruby
if arg_is_missing?
exit 1
end
```
The non-zero status code means this will work great in a scripting scenario,
like `ruby script.rb && echo 'success'`. If the script has to exit early, it
won't print 'success'.
That's fine, but it doesn't give the program a chance to tell us _why_ the
program exited early.
`Kernel` has another method
[`abort`](https://ruby-doc.org/core-3.1.2/Kernel.html#method-i-abort) that does
the same thing as `exit 1` while also printing a message to `STDERR`.
```ruby
if arg_is_missing?
abort 'The missing argument must be supplied'
end
```
This is handy if you want to communicate more than just the error code. The
program still exits early with an error code of `1`. And it prints that message
to `STDERR`.
[source](https://stackoverflow.com/a/23340693/535590)