Skip to content

Instantly share code, notes, and snippets.

@kenn
Created November 16, 2012 23:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenn/4091803 to your computer and use it in GitHub Desktop.
Save kenn/4091803 to your computer and use it in GitHub Desktop.
A proposal for new syntax construct to define errors

When we define an error class in a module, we do one of the following.

module App
  class Error < StandardError; end
  class ServerError < Error; end
  class ClientError < Error; end
end
module App
  Error = Class.new(StandardError)
  ServerError = Class.new(Error)
  ClientError = Class.new(Error)
end

IMO, the ugliness of the syntax is partly responsible that not many libraries have custom errors of their own, even when it makes sense.

It would be great if we could write this way instead:

module App
  define_error Error                            # inherits StandardError by default
  define_error ServerError, ClientError < Error # inherits App::Error
end

Which would encourage define errors.

I realized that the same could apply to empty class inheritance in general, but errors are much more likely to inherit without adding any features - thus naming specifically define_error here.

@matz
Copy link

matz commented Nov 16, 2012

If you put ":" before the error names, you can define it by yourself.

  define_error :Error
  define_error :ServerError, :ClientError, super: Error

@kenn
Copy link
Author

kenn commented Nov 17, 2012

I agree that it's doable as a gem that way.

I just think if the syntax was a built-in, more libraries would be encouraged to define custom errors, without worrying about external dependency other than ruby itself.

So, ticket filed: http://bugs.ruby-lang.org/issues/7376

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment