Skip to content

Commit

Permalink
Add API error class to handle API error message
Browse files Browse the repository at this point in the history
  • Loading branch information
aidewoode committed Sep 18, 2023
1 parent 08d8954 commit b243e59
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
3 changes: 2 additions & 1 deletion app/controllers/api/v1/api_controller.rb
Expand Up @@ -6,7 +6,8 @@ class ApiController < ApplicationController
skip_before_action :verify_authenticity_token

rescue_from ActiveRecord::RecordNotUnique do
render json: {error: "RecordNotUnique", message: t("error.already_in_playlist")}, status: :bad_request
# render json: {type: "RecordNotUnique", message: t("error.already_in_playlist")}, status: :bad_request
render json: ApiError.new(:record_not_unique, t("error.already_in_playlist")), status: :bad_request
end

private
Expand Down
18 changes: 18 additions & 0 deletions app/models/api_error.rb
@@ -0,0 +1,18 @@
# frozen_string_literal: true

class ApiError
TYPES = {
record_not_unique: "RecordNotUnique"
}

attr_reader :type, :message

def initialize(type_key, message)
@type = TYPES[type_key]
@message = message
end

def to_json(*_args)
{type: @type, message: @message}.to_json
end
end
Expand Up @@ -69,7 +69,7 @@ class Api::V1::CurrentPlaylist::SongsControllerTest < ActionDispatch::Integratio
response = @response.parsed_body

assert_response :bad_request
assert_equal "RecordNotUnique", response["error"]
assert_equal "RecordNotUnique", response["type"]
assert_not_empty response["message"]
end
end
Expand Up @@ -25,7 +25,7 @@ class Api::V1::FavoritePlaylist::SongsControllerTest < ActionDispatch::Integrati
response = @response.parsed_body

assert_response :bad_request
assert_equal "RecordNotUnique", response["error"]
assert_equal "RecordNotUnique", response["type"]
assert_not_empty response["message"]
end
end

0 comments on commit b243e59

Please sign in to comment.