Skip to content

Instantly share code, notes, and snippets.

@42thcoder
Last active August 28, 2015 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 42thcoder/5fdec9d278ea4adfd7df to your computer and use it in GitHub Desktop.
Save 42thcoder/5fdec9d278ea4adfd7df to your computer and use it in GitHub Desktop.
异常处理
class Api < Grape::API
class << self
def log_exception(exception)
trace = exception.backtrace
message = "\n#{exception.class} (#{exception.message}):\n"
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
message << " " << trace.join("\n ")
Rails.logger.error(message)
end
end
rescue_from ActiveRecord::RecordNotFound do |exception|
Api.log_exception(exception)
rack_response(MultiJson.dump({ message: '未找到', status: 404, success: false }), 404 )
end
rescue_from :all do |exception|
Api.log_exception(exception)
rack_response(MultiJson.dump({ message: "未知错误", status: 500, success: false }), 200)
raise exception
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment