RestfulError
Define your error with status code. Raise it and you will get formatted response with i18nized message.
Installation
Add this line to your application's Gemfile:
gem 'restful_error'
And then execute:
$ bundle
Usage
Pure ruby
ex = RestfulError[404].new
ex.restful.code # => 404
ex.restful.reason_phrase # => "Not Found"
your custom error by subclassing
class ::NoSession < RestfulError[404]; end
# or
class ::NoSession < RestfulError::NotFound; end
your custom error with http_status
class OAuthController < ApplicationController
# define http_status and include RestfulError::Helper
class PermissionError < StandardError
include RestfulError::Helper
def http_status = 401
end
# or
class PermissionError < StandardError
include RestfulError::Helper
def http_status; :unauthorized; end
end
end
PermissionError.new.restful.reason_phrase # => "Unauthorized"
With Rails
config.exceptions_app
will automatically set.
raise me in request
class PostsController < ApplicationController
before_action do
raise RestfulError[401] unless current_user
# or
raise RestfulError:: unless current_user
end
end
Multi format response
get '/posts/new'
#=> render 'restful_error/show.html' with @status_code and @message
post '/posts.json'
#=> { status_code: 401, message: "Sign in required" } or write your json at 'restful_error/show.json'
get '/session.xml'
#=> "<error><status_code type="integer">401</status_code><message>Sign in required</message></error>" or write your xml at 'restful_error/show.xml'
I18n
ja:
restful_error:
unauthorized: ログインしてください #401
not_found: ページが存在しません #404
library defined error
config.action_dispatch.rescue_responses["CanCan::Unauthorized"] = 401
# or
config.action_dispatch.rescue_responses["CanCan::Unauthorized"] = :unauthorized
I18n
ja:
restful_error:
no_session: セッションがありません
oauth_controller/require_twitter_login: Twitterログインが必要です
can_can/unauthorized: 権限がありません
active_record/record_not_found: 要求されたリソースが存在しません
custom message
class RequireLogin < StandardError
def initialize(provider = 'Unknown')
@provider = provider
end
def status_code
:unauthorized
end
def
I18n.t('restful_error.require_login', provider: provider)
end
end
Contributing
- Fork it ( https://github.com/kuboon/restful_error/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request