title: Sinatra Error Handling in Ruby
body: <p>I have a simple Sinatra rest and I am having trouble trapping an error. I also admit I am fairly new to Ruby and Sinatra.</p>
  
  <p>When I raise and error in the post endpoint I want to report the incoming document. I need to either 1) handle the error within the post result (where I have access to @incoming) or 2) pass the incoming document to the error and report it there.</p>
  
  <p>What is a better option, option 1 or option 2? </p>
  
  <ul>
  <li>If I stay with option 1, how do I prevent error from picking up the error (as it seems to be doing now)</li>
  <li>If I go to option 2, how do I pass incoming to error?</li>
  </ul>
  
  <p>Below is a sample of my code:</p>
  
  <pre><code>post ('/result') do 
  
    begin  
    @incoming = JSON.parse(request.body.read)
  
    //do something that causes an error
    rescue
       e = env['sinatra.error']
       url = request.url
       ip = request.ip
  
       @actlogpassblock = {  :message =&gt; e.message,
                          :path =&gt; url,
                          :ip =&gt; ip,
                          :timestamp =&gt; Time.new,
                          :type =&gt; "500",
                          :sub =&gt; "RES",
                          :payload =&gt; @incoming
                        }        
      action_log.insert(@actlogpassblock)
      status 500 
    end
  end
  
  error do
     status 500 
     e = env['sinatra.error']
     url = request.url
     ip = request.ip
     backtrace = "Application error\n#{e}\n#{e.backtrace.join("\n")}"
  
    @actlogpassblock = {  :message =&gt; e.message,
                          :path =&gt; url,
                          :ip =&gt; ip,
                          :timestamp =&gt; Time.new,
                          :type =&gt; "500",
                          :backtrace =&gt; backtrace
                        }        
    action_log.insert(@actlogpassblock)
    {:result =&gt; 'Ah Shucks! Something went wrong'}.to_json
  end
  </code></pre>