Merb Custom Exceptions

Posted by Peter
on Nov 21, 08
Adding your own custom exceptions in Merb is pretty easy and I'm adding this post basically for those lazy ones that search or ask before reading the documentations including myself.

In the source code docs is well explained you can extend any of the HTTPError classes and add the required action to your Exceptions controller, say:


class Exceptions < Merb::Controller
def user_not_found
render :format => :html
end
end


Create a custom view in app/view/exceptions/user_not_found.html.erb

And I extended in my own User model at the bottom:


class UserNotFound < Merb::ControllerExceptions::NotFound
end


or you could just extend Exception and define the HTTP error status in your method in exceptions controller.

Now you can start raising sweet exceptions:


raise UserNotFound unless @user