0
我想在Sinatra中編寫一個接受臨時CSV文件作爲參數的API。如果文件類型不是text/csv或者csv沒有電子郵件列,我想提出異常,並且我希望確認頁面只顯示錯誤消息。我想象它看起來是這樣的:如何優雅地處理異常在Sinatra API
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
但是,任何時候不符合這些條件之一,我得到這樣NoMethodErrors等我只想API停止執行,並返回真難看的錯誤信息確認頁面上的錯誤消息。我該怎麼做呢?