Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention for naming Ruby exceptions

I already have quite a number of libraries published. What I haven't decided yet is how to name my exceptions. The Ruby standard library always names the exceptions as such (a noun that is Exception or Error) - for example

  • RuntimeError
  • EOFError
  • ThreadError

Rails, in contrast, uses shortened exception names, like RecordInvalid and so on.

If I write libraries, and most of them are not Rails-related, which naming convention should I use? I must admit that the Rails "shortened names" appeal more to me, because when an exception happens you already see that it is an exception or an error of some kind because it pops up in the logs/debugger/stderr.

like image 995
Julik Avatar asked Dec 21 '22 08:12

Julik


2 Answers

Here's how I do it.

Does the name of the exception make it clear what's wrong? If yes, you're done. If not, add an Error suffix.

So using your example:

  • ThreadError: Here Thread is already a constant in ruby, and also a poor descriptor of an exceptional state. So a suffix is needed to denote some generic error in a thread.
  • RecordInvalid: In this case the name of the exception clearly states what's wrong. RecordInvlaidError would be redundant.

Another way to think of it might be generic vs specific.

  • ThreadError: Generic error, something bad happened with a thread, don't know exactly what, but it wasn't good. So this describe some sort of "error" in a "thread".
  • RecordInvalid: Specific error, this record right here has a specific problem with its data integrity and can't saved. So the "record" is "invalid", and that's all you need to say.
like image 128
Alex Wayne Avatar answered Jan 01 '23 14:01

Alex Wayne


Personally, I'm in the Error camp, but only when it feals natural. Putting Error on the end makes it clear what the class is, that it's not a normal object, etc. I find Exception a little long for my taste, and lack of suffix too ambiguous.

like image 35
Linuxios Avatar answered Jan 01 '23 15:01

Linuxios