Skip to content

Instantly share code, notes, and snippets.

@panthomakos
Created September 20, 2011 22:57
Show Gist options
  • Save panthomakos/1230673 to your computer and use it in GitHub Desktop.
Save panthomakos/1230673 to your computer and use it in GitHub Desktop.
Custom Error Messages in Ruby
class Group
module Error
class Standard < StandardError; end
class AlreadyAMember < Standard
def message
"You are already a member of this group."
end
end
class NotPermittedToJoin < Standard
def message
"You don't have the proper permissions to join this group."
end
end
end
def join user
raise Error::NotPermittedToJoin unless self.permitted?(user)
raise Error::AlreadyAMember if self.member?(user)
self.members.create :user => user
end
end
class GroupsController < ApplicationController
def join
@group = Group.find(params[:id])
@group.join current_user
flash[:notice] = "Welcome to the Group!"
redirect_to @group
rescue Group::Error::Standard => exception
flash[:error] = exception.message
render :action => 'request'
end
end
@panthomakos
Copy link
Author

An improved and more OOP approach to this example can be found here.

@aruprakshit
Copy link

I liked this approach... +1

@SaimonL
Copy link

SaimonL commented Apr 20, 2018

+1
How do I pass params to my custom exception?

Ex:

raise Error::AlreadyAMember.new(user)

And then in the Error class

def initialize(response)
    @response = response
 end

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