I'm doing an HTTP request from a Rails action like so:
class TeamController < ApplicationController
def test
_uri = 'http://v.youku.com/player/getPlayList/VideoIDS/XNjQyNjg3ODg0_ev_5'
_html_response = nil
open(_uri) do |http|
_html_response = http.read
end
render text: _html_response
end
end
But I get the error:
wrong status line: "TTP/1.1 302 Found"
But I used the same code in a simple Ruby file and I got the response without any errors. What am I doing wrong?
thanks,I find the reason,that's because my ubuntu vm is forbided to visit this site.sheet!
Related
I am using appsignal gem to track if there is an error processing in my app.
This case i do call external API using faraday.
def truck_information(req_params)
response = #conn.post('truck/info') do |req|
req.headers['Content-Type'] = 'application/json'
req.body = req_params
end
return JSON.parse(response.body) if response_successful?(response)
response_error(response)
end
def response_successful?(response)
response.status == 200
end
def response_error(response)
err = NctError, "Code: #{response.status}, response: #{response.body}"
Appsignal.set_error(err)
raise NctError, I18n.t('error_messages.ppob.server_error')
end
my truck_information is used to call external api. and if success i will parse it to json. but if error i will call response_error method parser to create custom class error (NctError) and i want to send to appsignal to show the error without breaking the application process.
But when i was tested it, it doesn't send to appsignal. How to do send error to appsignal, even if it doesn't crash a request? because i need to track the error.
Thank you
You could try Appsignal.send_error
Appsignal.send_error(err)
If above doesn't work either, then set_error and send_error may only work with Exception:
def response_error(response)
raise NctError, I18n.t('error_messages.ppob.server_error')
rescue => e
Appsignal.send_error(e) do |transaction|
transaction.params = { code: response.status, response: response.body }
end
end
Within an engine w/ an API, when querying the API an exception is thrown, but the server response is not using the response specified, and instead rendering a default debug response (in production).
I can confirm that the exception is caught by the controller:
Started GET "/api_v2/admin/submissions?system_id=123&spt_id=123" for
127.0.0.1 at 2019-03-15 10:04:37 -0400
Processing by ApiV2::Admin::SubmissionsController#show as JSON
Parameters: {"system_id"=>"123", "spt_id"=>"123"}
[3, 12] in /....../emp_api_v2/app/controllers/emp_api_v2/application_controller.rb
3:
4: before_action :doorkeeper_authorize!
5:
6: rescue_from ::ActiveRecord::RecordNotFound do |e|
7: byebug
=> 8: response(:standard_error, 500, "Hello World")
9: end
10:
11: def doorkeeper_unauthorized_render_options(error: nil)
12: { json: { message: "Not authorized" }, status: 403 }
(byebug) cont
Completed 500 Internal Server Error in 5220ms (ActiveRecord: 0.0ms)
ActiveRecord::RecordNotFound - Couldn't find Emp::System with 'id'=123:
The server is expected to respond with 500 Server Error not the debug error stacktrace.
Why are there two responses, even though the controller catches the exception and runs a response method.
NOTE: This happens in dev and prod ! Server responds with 500 first (my catch response) but then with a stacktrace and 404 (As this is the source of the error and correct exception). It breaks my tests as the past response was 500. I was not able to revert my server to the old behavior by: reinstalling ruby, reinstalling rails + all gems + rolling back all changes throughout the repo. This behavior seems to be externally set by a ENV variable or something else.
I'd be grateful for any insight.
Edit: The (api) app controller looks like this:
module ApiV2
class ApplicationController < ActionController::API
before_action :doorkeeper_authorize!
rescue_from ::ActiveRecord::RecordNotFound do |e|
response(:standard_error, 500, "Hello World")
end
def doorkeeper_unauthorized_render_options(error: nil)
{ json: { message: "Not authorized" }, status: 403 }
end
end
end
Edit 2: I was able to get the correct response by wrapping the call in a rescue block. That code will result in a lot of begin/rescue blocks though as each of them has a specific error message.
begin
system = Emp::System.find(sys_id)
rescue
render json: { status: 500, content: "Specific Error msg" } and return
end
Originally i had a method as follows:
def handle_exception(message, &block)
begin
block.call
rescue Exception => e
render json: { message: message }, status: 500 and return
end
end
This will result in double render error as it's not returning from the top-level method but from the block.
Im trying to reproduce the following request using httparty:
curl --verbose --data '{"username":"my_user#mail.com", "password":"my_password"}' http://my_page/api/user/authenticate
This is what I'm doing:
class RequestParty
include HTTParty
def initialize(base_uri)
self.class.base_uri base_uri
end
def post(endpoint, options)
self.class.post(endpoint, options)
end
end
RequestParty.new("http://my_page/api").post("/user/authenticate",{"username" => "my_user#mail.com", "password" =>"my_password"})
But I keep getting 500 Internal Server Error.
Whay am I doing wrong?
I have a bit of my Ruby/Rails (Ruby 2.0.0p195, Rails 3.2.13) project that works as a proxy; that is, you pass it a URL, it goes out and fetches the page, and presents it to you. This generally works as expected, but it seems to munge certain characters (such as è).
A simplified version of the controller is this:
class HomeController < ApplicationController
def geoproxy
require 'net/http'
require 'timeout'
rawurl = CGI::unescape(params[:url])
fixedurl = rawurl.gsub('\\', '%5C') # Escape backslashes... why oh why???!?
r = nil;
status = 200
content_type = ''
begin
Timeout::timeout(15) { # Time, in seconds
if request.get? then
res = Net::HTTP.get_response(URI.parse(fixedurl))
status = res.code # If there was an error, pass that code back to our caller
#page = res.body.encode('UTF-8')
content_type = res['content-type']
end
}
rescue Timeout::Error
#page = "TIMEOUT"
status = 504 # 504 Gateway Timeout We're the gateway, we timed out. Seems logical.
end
render :layout => false, :status => status, :content_type => content_type
end
end
The corresponding view is quite simple:
<%= raw #page %>
When I use this proxy to fetch XML containing an è (for example), I get the following error:
Encoding::UndefinedConversionError in HomeController#geoproxy
"\xE8" from ASCII-8BIT to UTF-8
This error occurs at the following line:
#page = res.body.encode('UTF-8')
If I remove the .encode(), the error is resolved, but my XML contains a placeholder instead of the è.
How can I get my project to display the XML properly?
Could you check if the following code works for you? I was able to fix similar problem of mine with it.
#page = res.body.force_encoding('Windows-1254').encode('UTF-8')
class MyTestController < ApplicationController
def index
render_text "hello world"
end
end
This is what I am getting when I go to http://127.0.0.1:3000/My_Test/ :
NoMethodError in My testController#index
undefined method `render_text' for #
RAILS_ROOT: C:/rails/rails_apps/cookbook
Application Trace | Framework Trace | Full Trace
app/controllers/my_test_controller.rb:5:in `index'
Request
Parameters:
None
Show session dump
Response Headers:
{"cookie"=>[], "Cache-Control"=>"no-cache"}
please keep in mind i am following this tutorial:
http://oreilly.com/pub/a/ruby/archive/rails.html?page=2
That tutorial is very old and out of date. The render_text method no longer exists. Try the following instead:
def index
render :text => "hello world"
end