Keeping API Errors Clean

Derek Hammer
Jun 25, 2018 · Unlisted
{ "type": "SomeError", "message": "Something went wrong!" }
class CartsController < ApplicationController
def show
errors, cart = CartRepository.new.fetch_cart(params.require(:id))
if errors.none?
render json: { content: cart }
else
render json: { errors: errors }, status: 422
end
end
end
ValidationError = Struct.new(:type, :message, keyword_init: true)
def fetch_cart(id)
cart = Cart.find_by(id: id)
return [[ValidationError.new(type: 'ResourceNotFound', message: 'Cart not found')], nil] if cart.nil?
[[], cart]
end
CART_NOT_FOUND_ERROR = ValidationError.new(type: 'ResourceNotFound', message: 'Cart not found')def fetch_cart(id)
cart = Cart.find_by(id: id)
return [[CART_NOT_FOUND_ERROR], nil] if cart.nil?
[nil, cart]
end
RSpec.define CartsController do
it 'should return resource not found error when id does not exist' do
get :show, id: -1
expected_value = {
errors: [CartRepository::CART_NOT_FOUND_ERROR]
}
expect(response.body).to eq(expected_value.to_json)
end
end
# No need to define ValidationError anymore, its in the gem
# ValidationError = Struct.new(:type, :message, keyword_init: true)
CART_NOT_FOUND_ERROR = CleanErrors::ValidationError('ResourceNotFound')

Square Corner Blog

Buying and selling sound like simple things - and they should be. Somewhere along the way, they got complicated. At Square, we're working hard to make commerce easy for everyone.

Unlisted

Derek Hammer

Written by

Square Corner Blog

Buying and selling sound like simple things - and they should be. Somewhere along the way, they got complicated. At Square, we're working hard to make commerce easy for everyone.