Last active
July 27, 2018 15:03
-
-
Save fedorkk/6636524fe93fffca5b54a2d1fccb6ffe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Обработка ошибок через возвращаемые параметры | |
class MyServiceObject | |
def self.call(params) | |
response = SomeApi.call(params) | |
if response.code == 500 | |
# Если api ответил некорректно то возвращаем ошибку | |
# (тут всего один метод, но если их будет много, то придется возвращать по цепочке) | |
{ status: 'failed', messages: 'Api error!' } | |
else | |
{ status: 'OK', data: response.body } | |
end | |
end | |
end | |
class MyController < ApplicationController | |
def index | |
result = MyServiceObject.call(params) | |
if result[:status] == 'OK' | |
render json: result[:data] | |
# Выводим ошибку полученную из ServiceObject | |
elsif result[:status] == 'failed' | |
render json: { errors: result[:messages] }, code: 400 | |
end | |
end | |
end | |
# Обработка ошибок через Exception | |
class ApiException < StandartError; end | |
class MyServiceObject | |
def self.call(params) | |
response = SomeApi.call(params) | |
# Райзим ошибку, выполнение сразу прерывается и ошибка всплывает наверх автоматически | |
raise ApiException if response.code == 500 | |
response.body | |
end | |
end | |
class MyController < ApplicationController | |
def index | |
# Здесь можно сразу рендерить, не думая об ошибках, они пройдут мимо | |
render json: MyServiceObject.call(params) | |
# А здесь уже обрабатываем только ошибку, не заботясь об остальном | |
rescue ApiException => e | |
render json: { errors: e.message }, code: 400 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment