Created
March 14, 2022 21:50
-
-
Save RomanTurner/10d442122c3c41a91364518ed5e02846 to your computer and use it in GitHub Desktop.
Error Class for JSON API can be extended to serialize different execptional creatures.
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 ErrorSerializer | |
attr_accessor :request, :params, :errors | |
def initialize(request, params, errors = [], exception = nil) | |
@request = request | |
@params = params | |
@errors = errors | |
@exception = exception | |
end | |
def serialize | |
{ | |
errors: | |
@errors.map do |error| | |
{ | |
id: @params[:id], | |
status: error[:status], | |
title: error[:title], | |
message: error[:message], | |
source: @request.parameters.merge({ url: @request.url }), | |
} | |
end, | |
}.to_json | |
end | |
def not_found | |
@errors = [ | |
{ | |
status: :not_found, | |
message: @exception, | |
title: 'ActiveRecord::RecordNotFound', | |
}, | |
] | |
serialize | |
end | |
def conflict | |
@errors = [ | |
{ | |
status: :conflict, | |
message: "Lead already scanned for attendee #{@params[:id]}", | |
exception: @exception, | |
title: 'ActiveRecord::RecordNotUnique', | |
}, | |
] | |
serialize | |
end | |
def unprocessable_entity | |
@errors = [ | |
{ | |
status: :unprocessable_entity, | |
message: @exception, | |
title: 'ActiveRecord::RecordInvalid', | |
}, | |
] | |
serialize | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment