display error message thrown by ms sql in ruby on rails - ruby-on-rails

i've been looking for a solution for weeks now. yet still failed..i have stored procedure that was called using in ruby on rails..in that stored proc i have validations and thrown using raiserror.
ex. raiserror("StartDate must be less than EndDate")
in my ruby on rails controller
def save
begin
M.find_by_sql "EXEC spTestProc '3/15/2010', '3/1/2010'"
rescue Exception => e
render :js => alert(e.message);
end
but instead i get the error message "StartDate must be less than EndDate", I got this error message "DBI::DatabaseError: 37000 (50000) [Microsoft][ODBC SQL Server Driver][SQL Server]StartDate must be less than EndDate..: Exec spTestProc '3/15/2010', '3/1/2010'"
I need to display the error message thrown by my stored proc, but i got some additional message that I dont like to display like "DBI::DatabaseError...etc." how can I do this?
thanks.

Use regular expression to remove the unwanted text.
e.message.gsub(/(^.*SQL Server\])|(: Exec spTestProc.*$)/i, '')
# this will return StartDate must be less than EndDate..

Related

Is there a list of JSON parse error codes?

I'm trying to provide a good experience to users that are using JSON and the parser is on the backend (Ruby).
Most of the time, when you get a badly formatted JSON payload the error is of the format XXX unexpected token at '<entire payload here>'. That's not very user-friendly nor practical.
My question is: Is there a list of the XXX error codes that could help create better error messages that could be understood by beginners and not-really-tech-people?
Thanks!
XXX in this kind of errors is not a special code of the error. It is just a line number from the file where this error was raised. For example, for Ruby 2.5.1 you'll get JSON::ParserError (765: unexpected token at https://github.com/ruby/ruby/blob/v2_5_1/ext/json/parser/parser.rl#L765
You can find a list in the documentation for the module.
Think this covers it:
JSON::JSONError
JSON::GeneratorError
JSON::GenericObject
# The base exception for JSON errors.
JSON::MissingUnicodeSupport
# This exception is raised if the required unicode support is missing on the system. Usually this means that the iconv library is not installed.
JSON::NestingError
# This exception is raised if the nesting of parsed data structures is too deep.
JSON::ParserError
# This exception is raised if a parser error occurs.
JSON::UnparserError
# This exception is raised if a generator or unparser error occurs.
JSON::JSONError is the parent class, so you can rescue from that and provide per-error-class messages as needed.
I feel it's worth noting that in my experience the vast majority of errors relating to JSON are of the class JSON::ParserError. Another common issue worth considering is getting ArgumentError if nil is passed as an argument.
As an example of how this could be used, you could work with something like the following:
begin
JSON.parse(your_json)
rescue JSON::JSONError, ArgumentError => e
{ error: I18n.t(e.to_s) } # <- or whatever you want to do per error
end
Hope that helps - let me know how you get on :)

How do I handle errors when using api_auth gem?

Currently for a project I am using api_auth gem. I am hitting on an external api in a function by making a signed request. Currently my code looks like this.
access_id = "someKey"
secret_key = "someRandomGeneratedKey"
request = RestClient::Request.new(url: 'serverUrl', method: get, headers:'headers')
#signed_request = ApiAuth.sign!(access_id, secret_key, request)
#signed_request.execute
I am unable to apply any error handling code to that last statement where I execute the request. Any suggestions?
You have to use begin rescue block to exception handling.
begin
#TODO Exception occurring statement
rescue
#Exception handling code
end
As you should only rescue specific exception, rather than all.
So as your code suggest that you are using rest_client & api-auth gem so from documentation you can get list of exception that this gem raise.
Example - For rest_client below exceptions need to be handled. (probably this is the solution of your problem, just replace last line as given below)
begin
#signed_request.execute
rescue RestClient::ExceptionWithResponse, URI::InvalidURIError, RestClient::InternalServerError => err
p err
end
There are few Exceptions also generated by api-auth gem also like
ApiAuth::ApiAuthError, ApiAuth::UnknownHTTPRequest so you need to rescue all this exceptions.
Reference link -
http://www.rubydoc.info/gems/api-auth/1.4.0/
Thanks!

Rails App with Sinatra engine - How to avoid rails errors?

Problem: When running specs the output is very confusing, instead of saying where the error lies it just throws misleading errors
This is inside the rails lib folder, and it's mounted on the routes.rb
# lib/engines/users/app.rb
module Engines
module Users
class App < Sinatra::Base
get '/api/v1/users/me' do
raise 'runtime error here'
end
get '/api/v1/another-route' do
# something here
status 200
end
end
end
end
The spec file looks something like this:
it 'returns a 200' do
get '/api/v1/users/me', auth_attributes
expect(last_response.body).to eq 'something' # added to clarify my point, it's not the response status that I care of.
expect(last_response.status).to be 200
end
error:
Failure/Error: expect(last_response.status).to be 200
expected #<Fixnum:401> => 200
got #<Fixnum:1001> => 500
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.
expected error:
RuntimeError:
runtime error here
Another route also fails:
it 'something' do
get '/api/v1/another-route', auth_attributes
expect(last_response.status).to be 401
json = JSON.parse(last_response.body).with_indifferent_access
expect(json[:message]).to eql "You have been revoked access."
end
error: Prints a massive html output which I believe is the rails backtrace html output
expected error: none as this endpoint doesn't raise an error
My question is if there's a way to:
Stop rails from dealing with this, so it gives the actual output
Avoid the entire engine to fail because one route raise exception
I believe that by solving the first point, the second one gets fixed too.
Thank you for your time
In order to solve my problem I've discovered that on the spec_helper the ENV['RACK_ENV'] was not being set, setting it to test resolves the problem and throws the exception I need in order to debug my code.
This happens because https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1832
set :show_exceptions, Proc.new { development? }
development? returned true when in fact should be false (needed the RACK_ENV set to test)
Now I get the correct output.

Read the content of a file and display with line numbers on the view

I am trying to write code to read a Ruby script entered by the user and stored it in a temp file, then pass that temp file to jruby -c temp_file to do syntax validation.
If any errors are found, I have to show the errors, along with the script entered by the user with line numbers.
How would I do this?
If there is a syntax error you see the failing line number:
blah.rb:2: syntax error, unexpected '.'
So just split your script on newline (\n) and thats your error line (1 index based of course).
If I understand correctly what you are trying to achieve, you can use jruby-parser (install gem install jruby-parser) with JRuby to find line numbers where errors occur:
require 'jruby-parser'
# Read script file into a String
script = File.open('hello.rb', 'r').read
begin
JRubyParser.parse(script)
rescue Exception => e
# Display line number
puts e.position.start_line
# Display error message
puts e.message
end

Delphi SQLite Update causing errors to appear

I have used Inserts, selects, updates, deleted without problem all over the program but for some reason this specific section causes it to except and not run the SQL I send it.
I am trying to "UPDATE SectionTable(AreaID) VALUES ('+IntToStr(ActClient.AreaID)+') WHERE SectionID='+IntToStr(iCount)"
The section with the ID "iCount" exists deffinately. The ActClient.AreaID is "2" and its overwriting null data in the "SectionTable" table.
What is the problem here?
OpenDatabase(slDb);
sltb:=sldb.GetTable('SELECT * FROM SectionTable WHERE SectionID='+IntToStr(iCount));
OutputDebugString(PAnsiChar(sltb.FieldAsString(sltb.FieldIndex['SectionID'])+sltb.FieldAsString(sltb.FieldIndex['Gender'])+sltb.FieldAsString(sltb.FieldIndex['CompetitionID'])));
sSQL := 'UPDATE SectionTable(AreaID) VALUES ('+IntToStr(ActClient.AreaID)+') WHERE SectionID='+IntToStr(iCount);
sldb.ExecSQL(sSQL);
CloseDatabase(slDb);
I get this error message appear when this is ran.
---------------------------
Debugger Exception Notification
---------------------------
Project CompetitionServer.exe raised exception class ESQLiteException with message 'Error executing SQL.
Error [1]: SQL error or missing database.
"UPDATE SectionTable(AreaID) VALUES (2) WHERE SectionID=2": near "(": syntax error'. Process stopped. Use Step or Run to continue.
---------------------------
OK Help
---------------------------
UPDATE table SET column = expression, column = expression WHERE predicates

Resources