The case
I have a Rail 4 application controller with a index method in it like this:
def index
raise "Original Error"
rescue => e
puts "We caught: '#{e.inspect}'"
raise "Another Error"
end
I am catching the Original Error, handling it, massaging it, doing whatever i want it, and then throwing a completely different error out - Another Error.
The expectation
It is, therefore, expected that my Rails app will produce Another Error when i visit the index page of controller and not the Original Error.
The unexpected behavior
But i am actually getting the Original Error instead. Copying the logs of the controller#action here:
Started GET "/homepage" for 127.0.0.1 at 2019-02-06 18:50:19 +0800
We caught: '#<RuntimeError: Original Error>'
Completed 500 Internal Server Error in 205ms (Flexirest: 0.0ms for 0 calls | ActiveRecord: 9.7ms)
RuntimeError - Original Error:
app/controllers/homepage_controller.rb:6:in `index'
Why is it throwing the Original Error here instead of the Another Error?
However, the behavior in the console is still as expected
I copy-pasted the same index method lines into my Rails console and then called the index method directly from within the console. Here is the console output for that.
[49] pry(main)> def index
[49] pry(main)* raise "Original Error"
[49] pry(main)* rescue => e
[49] pry(main)* puts "We caught: '#{e.inspect}'"
[49] pry(main)* raise "Another Error"
[49] pry(main)* end
=> :index
[50] pry(main)> index
We caught: '#<RuntimeError: Original Error>'
RuntimeError: Another Error
from (pry):67:in `rescue in index'
[51] pry(main)>
¯\_(ツ)_/¯
Since Ruby 2.1 the Kernel#raise method has a default parameter for cause that's using the "ambient exception" $!:
raise(string, cause: $!)
The effect is that every exception raised while in a scope of an ambient exception (i.e. in a rescue block) will populate the cause attribute of the raised exception with the current exception, unless the caller specifies a different value for cause during raise.
Your webserver/middleware is probably digging up the cause chain to find the "root cause" error and showing that one, probably using something like e = e.cause until e.cause.nil?.
If you want to suppress this behavior you can specify nil as the cause during raise:
raise "Another Error", cause: nil
I am using paperclip with a rails app and always I get the following error:
I, [2015-06-06T20:10:25.310071 #37358] INFO -- : Command :: file -b --mime '/tmp/58e53d1324eef6265fdb97b08ed9aadf20150606-37358-ouvtzl.png'
I, [2015-06-06T20:10:25.317478 #37358] INFO -- : [paperclip] Content Type Spoof: Filename ruby.png (application/octet-stream from Headers, [#<MIME::Type:0x000000053624c8 #friendly={"en"=>"Portable Network Graphics (PNG)"}, #system=nil, #obsolete=false, #registered=true, #use_instead=nil, #signature=false, #content_type="image/png", #raw_media_type="image", #raw_sub_type="png", #simplified="image/png", #i18n_key="image.png", #media_type="image", #sub_type="png", #docs=[], #encoding="base64", #extensions=["png"], #references=["IANA", "[Glenn_Randers-Pehrson]", "{image/png=http://www.iana.org/assignments/media-types/image/png}"], #xrefs={"person"=>["Glenn_Randers-Pehrson"], "template"=>["image/png"]}>] from Extension), content type discovered from file command: image/png. See documentation to allow this combination.
I, [2015-06-06T20:10:25.349416 #37358] INFO -- : Command :: file -b --mime '/tmp/58e53d1324eef6265fdb97b08ed9aadf20150606-37358-1n574dp.png'
I, [2015-06-06T20:10:25.356667 #37358] INFO -- : [paperclip] Content Type Spoof: Filename ruby.png (application/octet-stream from Headers, [#<MIME::Type:0x000000053624c8 #friendly={"en"=>"Portable Network Graphics (PNG)"}, #system=nil, #obsolete=false, #registered=true, #use_instead=nil, #signature=false, #content_type="image/png", #raw_media_type="image", #raw_sub_type="png", #simplified="image/png", #i18n_key="image.png", #media_type="image", #sub_type="png", #docs=[], #encoding="base64", #extensions=["png"], #references=["IANA", "[Glenn_Randers-Pehrson]", "{image/png=http://www.iana.org/assignments/media-types/image/png}"], #xrefs={"person"=>["Glenn_Randers-Pehrson"], "template"=>["image/png"]}>] from Extension), content type discovered from file command: image/png. See documentation to allow this combination.
Mongoid::Errors::Validations (
Problem:
Validation of Mock failed.
Summary:
The following errors were found: Image has contents that are not what they are reported to be
Resolution:
Try persisting the document with valid data or remove the validations.):
app/api/mockaccino/api.rb:23:in `block (2 levels) in <class:API>'
Curl command for test:
curl -X POST -i -F image=#/home/user/workspace/ruby.png -F name=mock http://localhost:3000/api/mock
I am traying send an image and a parameter called "name" to the server and creating a model with this attribute and image.
Model:
class Mock
include Mongoid::Document
include Mongoid::Paperclip
field :name, type: String
has_mongoid_attached_file :image
validates_attachment_presence :image
validates_attachment_size :image, :less_than => 1.megabytes
validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/]
end
Controller (Grape):
desc "Create an mock."
params do
requires :name, type: String, desc: "Mock name"
requires :image, :type => Rack::Multipart::UploadedFile, :desc => "Image file."
end
post do
mock = Mock.create!(
name: params[:name],
image: ActionDispatch::Http::UploadedFile.new(params[:image])
)
end
curl -i -X POST -H "Content-Type:multipart/form-data" -F image=#\"./ruby.png\";type=image/png;filename=\"ruby.png\"" http://localhost:3000/api/mock
I have one user who is seeing it with various browsers.. I can't duplicate it on my local development server or on production. It works for me, doesn't work for them. Haven't been able to isolate anything that is different (tried PC vs Mac, various browsers, etc.)
Pushing paperclip back from 4.3 to 4.2.1 makes the issue go away. This switches activemodel and activesupport from 3.2 back to 3.0 and it eliminates the dependency on mimemagic. My guess is that it's something subtle and complex in mimemagic.
In my controller method, i am doing this
def update_item_category
Parse.init :application_id => "appid",
:api_key => "appkey",
:quiet => true
puts Parse::Query.new("Brands").eq("brand_id", "5").get
end
on ".get" i am getting "TypeError Exception: no implicit conversion of Pathname into String".
Please help me out.
We are deploying a rails app to Heroku. The app should be making a youtube api call, using the Trollop Gem as a command line parser. We keep getting this error back.
2014-07-30T23:17:57.526014+00:00 app[web.1]: Error: unknown argument '-p'.
2014-07-30T23:17:57.526020+00:00 app[web.1]: Try --help for help.
2014-07-30T23:17:57.526541+00:00 app[web.1]: Completed 500 Internal Server Error in 7466ms
This is what our Trollop code looks like.
def self.youtube_search(query)
youtube_service_api_name = "youtube"
youtube_api_version = "v3"
# opts = HTTParty.get("https://www.youtube.com/results?search_query=russia")
opts = Trollop::options do
opt :q, 'Search term', :source => String, :default => query
opt :maxResults, 'Max results', :source => :int, :default => 25
end
What's much stranger is that it was working an hour ago and now it's not. Does anyone have any ideas? This doesn't seem to be documented anywhere.
Trollop will fail when provided with undefined arguments. In your code the -q option is defined but -p is not.
Here are the relevant lines in the parse method:
trollop.rb
339 unless sym
340 next 0 if ignore_invalid_options
341 raise CommandlineError, "unknown argument '#{arg}'" unless sym
342 end
As for why it was working previously, perhaps you were passing -q then and inadvertently passing -p now?
yeah i got the same problem. unknown argument -p and the 500 internal error.
i decided to give up on Trollop and just hard code my own opts.
so i just initialized an opts hash and inserted key value pairs and no more problems.
I would like to check if the xml is valid. So, here is my code
require 'rexml/document'
begin
def valid_xml?(xml)
REXML::Document.new(xml)
rescue REXML::ParseException
return nil
end
bad_xml_2=%{aasdasdasd}
if(valid_xml?(bad_xml_2) == nil)
puts("bad xml")
raise "bad xml"
end
puts("good_xml")
rescue Exception => e
puts("exception" + e.message)
end
and it returns good_xml as result. Did I do something wrong? It will return bad_xml if the string is
bad_xml = %{
<tasks>
<pending>
<entry>Grocery Shopping</entry>
<done>
<entry>Dry Cleaning</entry>
</tasks>}
Personally, I'd recommend using Nokogiri, as it's the defacto standard for XML/HTML parsing in Ruby. Using it to parse a malformed document:
require 'nokogiri'
doc = Nokogiri::XML('<xml><foo><bar></xml>')
doc.errors # => [#<Nokogiri::XML::SyntaxError: Opening and ending tag mismatch: bar line 1 and xml>, #<Nokogiri::XML::SyntaxError: Premature end of data in tag foo line 1>, #<Nokogiri::XML::SyntaxError: Premature end of data in tag xml line 1>]
If I parse a document that is well-formed:
doc = Nokogiri::XML('<xml><foo/><bar/></xml>')
doc.errors # => []
REXML treats a simple string as a valid XML with no root node:
xml = REXML::Document.new('aasdasdasd')
# => <UNDEFINED> ... </>
It does not however treat illegal XML (with mismatching tags, for example) as a valid XML, and throws an exception.
REXML::Document.new(bad_xml)
# REXML::ParseException: #<REXML::ParseException: Missing end tag for 'done' (got "tasks")
It is missing an end-tag to <done> - so it is not valid.