Graphaware neo4j-php-client | Cannot catch Neo4jException - neo4j

I'm using Postgresql + Neo4j for my project. I need to rollback postgres queries if neo4j query has failed. So, I need to catch Neo4jException in my code. But couldn't done yet. Thanks for help.
require_once('pgconnect.php');
try{
$conn->beginTransaction();
//some pgsql code
$conn->commit();
require_once('neoconnect.php');
$result = $client->run("a query");
$conn = null;
}
catch(PDOException $e){
require_once('pgrollback.php');
}
this is my working code. But as you can see I don't have a catch block to catch neo4j exception. So I added this but no luck. also tried withNeo4jExceptionInterface as exception class (desperate times). (BTW I'm using wrong typed query to get exception)
catch(Neo4jException $ex){
//done smth
}
Also tried to do this without luck too.
$client->run("a query") or throw new Neo4jException();

I just tested and I have no issues catching an exception, can you maybe provide more code, what is in neoconnect.php for example ?
This is my test :
$client = ClientBuilder::create()
->addConnection('default', 'http://localhost:7474')
->build();
$query = 'INVALID QUERY';
try {
$result = $client->run($query);
} catch (\GraphAware\Neo4j\Client\Exception\Neo4jException $e) {
echo sprintf('Catched exception, message is "%s"', $e->getMessage());
}
-
ikwattro#graphaware ~/d/g/p/neo4j-php-client> php test.php
Catched exception, message is "Invalid input 'I': expected <init> (line 1, column 1 (offset: 0))
"INVALID QUERY"
^"⏎

Related

Python Glue job - Snowflake stored procedure not returning exact error message

I am trying to execute a snowflake stored procedure via python glue job, but when I get any error in the SQL statements in the stored procedure, I want the procedure to exit and that glue job should fail.
I am using this code in my snowflake stored procedure:
create or replace procedure schema.PROC_TEST
(input_sql varchar(16777216))
returns string not null
language javascript
as
$$
snowflake.execute({sqlText:`BEGIN TRANSACTION;`});
try
{
var QueryExec = INPUT_SQL+ ";";
var QueryResult = snowflake.execute({sqlText: QueryExec});
}
catch (err) // Catching any error if occurs in INPUT_SQL
{
result = 'Error: ' + err;
snowflake.execute({sqlText:`ROLLBACK;`});
return result;
throw err.message;
}
$$;
Now if I pass input query as below (here proc_test_final1 is an incorrect table name) :
insert into schema.proc_test_final1
select id, name, sal
from schema.proc_test_src;
Instead of throwing an error 'incorrect table name', the procedure returns a generic error like
Error: 090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back
I thought it might be because of ROLLBACK command so I tried removing the command but still it failed with the same above error. I also tried removing result variable in catch block but still above error was caught.
I want to catch the exact specific SQL error (syntax error/code error) in my glue job.
Below is my glue job code where I am catching the error:
input_sql = 'insert into schema.proc_test_final1 select id, name, sal from schema.proc_test_src'
try:
f_CallProc = "call TEST_PROC('"+input_sql+"');"
cur.execute(f_CallProc)
print(cur.fetchall())
cur.close()
ctx.close()
except snowflake.connector.errors.ProgrammingError as err:
print('Error: {0} ({1})'.format(err.msg, err.sfqid))
cur.close()
ctx.close()
sys.exit(1)
The error "Scoped transaction started in stored procedure is incomplete and it was rolled back" will happen when you run the SP that has explicit START TRANSACTION, but no explicit "ROLLBACK" or "COMMIT".
In my test, if I do not have below line:
snowflake.execute({sqlText:`ROLLBACK;`});
Your SP will fail with such error.
However, when I have this line, it will fail with below error instead:
Error: SQL compilation error:
Schema 'ERICLIN.SCHEMA' does not exist or not authorized.
Which I think is what you are after.
Can you please double check your SP again? Did you copy and paste the correct one?
By the way, your original SP won't run because there is no variable called "input_sql", it should be "INPUT_SQL", as every variable in Snowflake's SP is in UPPER case.
=========================
UPDATE
Please see below execution output:
create or replace procedure PROC_TEST
(input_sql varchar(16777216))
returns string not null
language javascript
as
$$
snowflake.execute({sqlText:`BEGIN TRANSACTION;`});
try {
var QueryExec = INPUT_SQL + ";";
var QueryResult = snowflake.execute({sqlText: QueryExec});
}
catch (err) {
result = 'Error: ' + err;
snowflake.execute({sqlText:`ROLLBACK;`});
return result;
}
$$;
call PROC_TEST('insert into schema.proc_test_final1 select id, name, sal from schema.proc_test_src');
+-----------------------------------------------------------+
| PROC_TEST |
|-----------------------------------------------------------|
| Error: SQL compilation error: |
| Schema 'ERICLIN.SCHEMA' does not exist or not authorized. |
+-----------------------------------------------------------+
Without the ROLLBACK call, it will produce an error same as yours:
create or replace procedure PROC_TEST
(input_sql varchar(16777216))
returns string not null
language javascript
as
$$
snowflake.execute({sqlText:`BEGIN TRANSACTION;`});
try {
var QueryExec = INPUT_SQL + ";";
var QueryResult = snowflake.execute({sqlText: QueryExec});
}
catch (err) {
result = 'Error: ' + err;
return result;
}
$$;
call PROC_TEST('insert into schema.proc_test_final1 select id, name, sal from schema.proc_test_src');
090232 (25000): Stored procedure execution error: Scoped transaction started in stored procedure is incomplete and it was rolled back.

How to check if a record was updating using Zend Framework's 2 Sql Adapter Class

I'm trying to test to see if an update query was successful with Zend Framework 2. I'm using the getAdapter()->query() methods but I'm unsure of how to actually test to see if anything was returned or if it actually executed. I know it is executing (as I can see the update working via mysql workbench) but I'm not sure on how to actually count or verify. Here is the code I have in place (which I know is wrong but I don't know what else to do):
$update = $this->update->table('stores')
->set(array('number_of_items' => $number))->where(array('store_name' => $this->store_name));
$query = $this->sql->getAdapter()->query($this->sql->buildSqlString($update), Adapter::QUERY_MODE_EXECUTE);
if ($query->count() > 0) {
// insert the items into the items table
$insert = $this->insert->into('items')
->columns(array('store_id', 'price', 'description'))
->values(array($row['store_id'], $price, $item_desc));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($insert),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
return true;
} else {
throw new \Exception("Error adding your item to the items table, please try again.");
}
} else {
// this is the exception being thrown
throw new \Exception("An error occurred while adding your item(s) to the store, please try again");
}
Now I know most likely count() will only work on select queries but I am unsure of how to test to see if the update and insert were successful.
Any help would be appreciated
Thanks
To test if update and insert were successful.
As per your code
try {
$affetedRows = $this->insert->into('items')
->columns(array('store_id', 'price', 'description'))
->values(array($row['store_id'], $price, $item_desc));
}catch (\Exception $e) {
var_dump($e->getMessage());exit; // see if any exaption Or error in query
}
}
var_dump($affetedRows ) // it will return number of affected rows.
Same for delete and update, after successfull execution delete and updateare also returns number of affected rows.
so if there is successfull exceution, you can check success of your query.
Thanks.

exception inside of OnException

I created a custom attribute, inheriting from HandleErrorAttribute:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
try
{
Utility.LogAndNotifyOfError(filterContext.Exception, null, true);
}
catch(Exception ex)
{
filterContext.Exception = ex;
}
}
}
, and then registered with:
filters.Add(new CustomHandleErrorAttribute());
This has always worked as intended. However a common problem with my log method is that it uses a custom event log source when writing to the event log, which the app pool account typically doesn't have the permissions to create. Creating the event log source is a simple powershell script, however I wanted to actually include that tidbit in the error:
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
The problem is that the catch in the OnException is never hit. When debugging, the custom error I throw from LogAndNotifyOfError instead triggers a second call to OnException, and the detail of my ErrorHandlerException is never seen. I want the asp.net error page that comes up to be with my custom error detail rather than the SecurityException that was originally raised.
You can even see the surrounding try in the displayed error:
Edit: Entire log method listed:
public static void LogAndNotifyOfError(Exception ex, String extraInfo, Boolean sendEmail)
{
//if the error handler itself faulted...
if (ex is ErrorHandlerException)
return;
string eventLogName = "Application";
string eventLogSource = "MySourceName";
String error = ex.ToString();
if (error.Length > 28000)
error.Substring(0, 28000);//event log is limited to 32k
error += "\r\n\r\nAdditional Information: \r\n"
+ "Machine Name: " + Environment.MachineName + "\r\n"
+ "Logged in user:" + App.CurrentSecurityContext.CurrentUser?.UserId + "\r\n"
+ extraInfo + "\r\n";
EventLog log = new EventLog(eventLogName);
log.Source = eventLogSource;
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{//this doesn't work - for some reason, OnError still reports the original error.
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
//if the email-to field has been set...
if (!String.IsNullOrEmpty(App.Config.General.ErrorHandlerSendToAddresses) && sendEmail)
{
//...then send the email
MailMessage email = new MailMessage();
email.To.Add(App.Config.General.ErrorHandlerSendToAddresses);
email.IsBodyHtml = false;
email.Subject = String.Format("Error in {0}", eventLogSource);
email.Body = email.Subject + "\r\n\r\n"
//+ "Note: This error may be occuring continuously, but this email is only sent once per hour, per url, in order to avoid filling your mailbox. Please check the event log for reoccurances and variations of this error.\r\n\r\n"
+ "The error description is as follows: \r\n\r\n"
+ error + "\r\n\r\n";
SmtpClient smtp = new SmtpClient();
smtp.Send(email);
}
}
I figured it out (sort of). It would appear that when the newly throw exception has an inner exception, it is only displaying that inner exception. It does not matter what the type is on the outer or inner exception.

Grails Controller - Could not catch a SocketException

When I try to catch an Exception in a controller method I could not catch SocketException. The controller action looks like:
def updateDeviceStartV1() {
try {
...
response.status = 200;
response.setContentType("application/octet-stream")
response.outputStream << responseService.encryptedResponse // byte[]
}
catch(Exception e) {
log.error "Server faced unexpected exception", e
response.status = 500;
...
}
The SocketException is thrown by line "response.outputStream << responseService.encryptedResponse" because the client unexpectedly close the connection. Nevertheless, this exception is not catched and the console receives standard exception display...
Am I doing something wrong?
I think that if the method where the exception is raised doesn't throw the exception explicitly (with a throws in the signature), it will be thrown as an UndeclaredThrowableException. Then the type in your catch just doesn't match it. Try catching SocketException instead. Or if you can just catch them all using catch(all).
Oh, take a look at this.

error while using groovy.sql Out parameter

I am trying to execute some stored procedures in groovy way. I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.
I am trying to call the stored procedure as:
sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode,
sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR),
sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs ->
params.city = rs.getString(2)
params.state = rs.getString(3)
}
I tried various ways like sql.call. I was trying to get output variable value after this.
Everytime error:
Message: Cannot register out parameter.
Caused by: java.sql.SQLException: Cannot register out parameter.
Class: SessionExpirationFilter
but this does not seem to work.
Can anyone point me in the right direction?
This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The following turned up from the Groovy source, perhaps it's of some help:
This line seems to be the origin of the exception:
http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173
This would seem to indicate that you have a Statement object implementing PreparedStatement, when you need the subinterface CallableStatement, which has the registerOutParameter() method which should be ultimately invoked.
Thanks Internet Friend,
If i write code like-
Sql sql = new Sql(dataSource)
Connection conn
ResultSet rs
try {
conn = sql.createConnection()
CallableStatement callable = conn.prepareCall(
"{call web_GetCityStateByZip(?,?,?,?,?)}")
callable.setString("#p_Zip",params.postalcode)
callable.registerOutParameter("#p_City",java.sql.Types.VARCHAR)
callable.registerOutParameter("#p_State",java.sql.Types.VARCHAR)
callable.registerOutParameter("#p_RetCode",java.sql.Types.INTEGER)
callable.registerOutParameter("#p_Msg",java.sql.Types.VARCHAR)
callable.execute()
params.city = callable.getString(2)
params.state = callable.getString(3)
}
It working well in JDBC way. But i wanted to try it like the previous code using sql.query/sql.call.
Any comments??
Thanks
Sadhna
groovy way could be this code:
def getHours(java.sql.Date date, User user) throws CallProceduresServiceException {
log.info "Calling stored procedure for getting hours statistics."
def procedure
def hour
try {
def sql = Sql.newInstance(dataSource.url, user.username, user.password, dataSource.driverClassName)
log.debug "Date(first param): '${date}'"
procedure = "call ${dbPrefixName}.GK_WD_GET_SCHEDULED_TIME_SUM(?, ?, ?, ?)"
log.debug "procedure: ${procedure}"
sql.call("{${procedure}}", [date, Sql.out(Sql.VARCHAR.getType()), Sql.out(Sql.VARCHAR.getType()), Sql.out(Sql.VARCHAR.getType())]) {
hourInDay, hourInWeek, hourInMonth ->
log.debug "Hours in day: '${hourInDay}'"
log.debug "Hours in week: '${hourInWeek}'"
log.debug "Hours in month: '${hourInMonth}'"
hour = new Hour(hourInDay, hourInWeek, hourInMonth)
}
log.info "Procedure was executed."
}
catch (SQLException e) {
throw new CallProceduresServiceException("Executing sql procedure failed!"
+ "\nProcedure: ${procedure}", e)
}
return hour
}
In my app it works great.
Tomas Peterka

Resources