Skip to content

Return errors as json objects instead of strings #722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/controllers/albums_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ def create
if @album.save
render json: transform_album_for_json(@album), status: :created
else
render json: @album.errors, status: :unprocessable_entity
render json: transform_errors_for_json(@album.errors.errors), status: :unprocessable_entity
end
end

def update
if @album.update(transformed_attributes)
render json: transform_album_for_json(@album), status: :ok
else
render json: @album.errors, status: :unprocessable_entity
render json: transform_errors_for_json(@album.errors.errors), status: :unprocessable_entity
end
end

Expand Down
10 changes: 10 additions & 0 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ def add_pagination_headers(collection)
response.headers['Access-Control-Expose-Headers'] = 'x-total-entries, x-total-pages, x-current-page, x-per-page, x-offset'
end

def transform_error_for_json(error)
result = %i[attribute type].index_with { |it| error.send(it) }
result[:options] = error.options.except(*ActiveModel::Error::CALLBACKS_OPTIONS, *ActiveModel::Error::MESSAGE_OPTIONS)
result
end

def transform_errors_for_json(errors)
errors.map { |it| transform_error_for_json(it) }
end

private

def authenticate_from_token
Expand Down