Reputation: 3844
I'm trying to write an API in Sinatra that accepts a temporary CSV file as a parameter. I want to raise an exception if the filetype isn't text/csv or if the CSV doesn't have an email column, and I wanted the confirmation page to simply display the error message. I imagined it to look something like this:
if params[:recipients_file]
raise ArgumentError, 'Invalid file. Make sure it is of type text/csv.' unless params[:recipients_file][:type] == "text/csv"
recipients_csv = CSV.parse(params[:recipients_file][:tempfile].read, {headers: true})
raise ArgumentError, 'Invalid CSV. Make sure it has an "email" column' unless recipients_csv.headers.include?('email')
recipients += recipients_csv.map {|recipient| recipient["email"]}
end
However, any time one of those conditions isn't met, I get really ugly error messages like NoMethodErrors
etc. I just want the API to stop execution and to return the error message on the confirmation page. How do I do this?
Upvotes: 0
Views: 1208
Reputation: 3103
Step 1. First, you should add this line of code in your main app.rb or server.rb(whatever the name of your file) so that it will catch your error block below.
set :show_exceptions, false
Step 2. The exception object can be obtained from the sinatra.error Rack variable. To catch all error then add this error block e.g. code error do...
error do
env['sinatra.error'].message
end
Upvotes: 0
Reputation: 223183
You should define an error
block:
error do
env['sinatra.error'].message
end
See http://www.sinatrarb.com/intro.html#Error for more details, including how to set up different error handlers for different exception types, HTTP status codes, etc.
Upvotes: 5