Try/Except python for error title containing a number - python-3.x

I have a python script and I am using a function from a library where an error is generated for some of the inputs to the function: (Error 200, reqID #####: ....). If an error is generated, then I would like the I would like the script to omit the entry and continue.
I am wondering how to use try - except to catch the error. My script looks as follows:
try:
contracts = ib.qualifyContracts(*contracts)
except ???:
pass
Error 200, reqId 18929: ...
Error 200, reqId 18928: ...
I've tried inserting Error 200 (both with and without quotation) after the except phrase but the errors are not being caught. Any suggestions are appreciated.
Thanks.
EDIT:
I believe the library is library is just printing error messages. Errors look as follows below.
Error 200, reqId 8: No security definition has been found for the request, contract: Option(symbol='SPY', lastTradeDateOrContractMonth='20220921', strike=85.0, right='P', exchange='SMART', tradingClass='SPY')
Error 200, reqId 9: No security definition has been found for the request, contract: Option(symbol='SPY', lastTradeDateOrContractMonth='20220921', strike=90.0, right='P', exchange='SMART', tradingClass='SPY')

Related

Groovy catch block not catching MultipleCompilationErrorsException

I am trying to catch an exception (MultipleCompilationErrorsException) but am having a hard time doing so (actually I am trying to catch all types of errors and exceptions if that matters). Here is what I have tried:
try {
some erroneous crap here
println("wtf! A")
} catch(Throwable all) {
println("caught!")
}
This works. caught! is shown as the output.
try {
try some erroneous crap here
println("wtf! A")
} catch(Throwable all) {
println("caught!")
}
This code errors out with:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: /tmp/g.groovy: 2: expecting '{', found 'some' # line
2, column 9.
try some crap here
^
1 error
So now that I have the exception name, I tried:
try {
try some erroneous crap here
println("wtf! A")
} catch(MultipleCompilationErrorsException e) {
println("caught!")
}
This errors out exactly like the above:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: /tmp/g.groovy: 2: expecting '{', found 'some' # line
2, column 9.
try some crap here
^
1 error
Can someone tell me what I am missing? How does one catch such an error/exception?
"Try Catch's" are generally used to handle exceptions that may pop up during the run time of your code. For example, you can try to run a command that requires a certain plugin/library to be imported but if the user doesn't have the respective plugin/library, then the "catch" will handle this exception.
In your case, it seems that you are trying to handle an actual error with the code syntax within your try block. The try block cannot run at all if the syntax is not correct (this would be the compilation error). My best advice would be to try running what ever is inside your try block first to see if it will throw an exception and then implement a try catch block.

How to stop testcase execution if request fails in soapui using script assertion?

If the soap request has a failure means Status != "HTTP/1.1 200 OK" , testCase should stop and no further steps should run
There is a way to do this in groovy, but i do not want an extra test step to be added in testcase
def headers = testRunner.testCase.getTestStepByName("RequestName").httpRequest.response.responseHeaders['#status#']
if (!headers.contains("HTTP/1.1 200 OK"))
{
testRunner.fail("" + headers + "Flow failed")
testRunner.fail("No futher testSteps will be run inside the current case")
}
Please note i cannot change below settings due to some other groovy code restriction
The reason for not changing above option i have a testcase where there are 10 steps. 1 is request and other 9 steps validate various things. So if i check the "Abort on error" option and step 3 fails. then none of the steps from 4 to 10 runs. So please provide a solution considering not using "abort" option
So could you please provide a solution for script assertion without ticking this option."Abort on error"
Since testRunner.fail is not available inside script assertion and also normal assertion (assert 0==1) does not stop testcase unless we tick the above setting. i am stuck with this limitations
You have access to testRunner through the context variable available in a script assertion, so why not something like:
def httpResponseHeader = messageExchange.responseHeaders
def headers = httpResponseHeader["#status#"]
log.info("Status: " + headers)
if (!headers.contains("HTTP/1.1 200 OK")) {
context.testRunner.fail("" + headers + "Flow failed")
context.testRunner.fail("No futher testSteps will be run inside the current case")
}
Thanks #craigcaulifield, your answer has helped me a lot.
Good to know that testRunner is available even in script assertion in a tricky way
Now using script assertion we can stop a testCase if request fails.
However when we run request alone not as part of testcase an error comes
cannot invoke method fail() on null object
This error comes because
context.testRunner.fail()
testRunner is only available during test Case execution and not individual testStep execution
So to overcome here is the code which can take care of both situation
def responseHeaders=messageExchange.responseHeaders
def status=responseHeaders["#status#"]
// Checking if status is successfully fetched i.e. Response is not empty
if(status!=null)
{
if(!status.contains("HTTP/1.1 200 OK"))
{
// context.testRunner is only available when the request is run as a part of testCase and not individually
if(context.testRunner!=null)
{
// marking the case fail so further steps are not run
context.testRunner.fail()
}
assert false, "Request did not returned successful status. Expected = [HTTP/1.1 200 OK] but Actual = " + status
}
}
else
{
if(context.testRunner!=null)
{
context.testRunner.fail()
}
assert false, "Request did not returned any response or empty response"
}

Is there any way to change the color of error message when I use throw statement?

I know some tools to change console's text color, such as chalk . But when I use throw statement to print error message and need to red it:
const chalk = require('chalk');
throw new Error(chalk.red('some error messages'));
It failed with no red color's error message:
?[31msome error messages?[39m
Is there any way to change the color of error message caused by throw statement?
You have to put your throw() call in a try/catch block. This way, you can catch your error and format it with console.log().
Example:
// The try/catch block
function run() {
try {
myAction();
}
catch (err) {
console.log('%c ' + err.message, 'background: red; color: white');
}
}
// Your action
function myAction() {
throw new Error('some error message');
}
Now you can just call run() and see the formatted error in the console.
Are you sure your console understands ANSI sequences? I mean, the browser console may not understand them at all, and Windows command line displays them properly only in Windows 10.
Generally you should avoid throwing ANSI-colored error messages, as it may not work on every system, and thus is a bad practice. Nevertheless throw alone should not break the sequence, as it is just a string of ASCII characters.
What may break it is console itself not understanding it. What you have pasted (?[31msome error messages?[39m) differs from a valid ANSI-colored text only by replacing the escape character (ASCII code 27) with "?". Thus I suspect you are trying to display the text in a console not suitable of interpreting ANSI codes. Use Windows 10 console or any Unix/Linux/MacOS X system console and it will work. In the consoles of webbrowsers and in Windows versions prior to 10 it won't.
If you need colored console output in webbrowser see this answer.

PostgreSQL How to use standard ERROR CODE and ERROR MESSAGE

I would like to use standard ERROR message and code of PostgreSQL.
Right now, I can achieve my goal, but I would like to know the best way I can use.
Here is my current function in database.
CREATE OR REPLACE FUNCTION Dugong.Forget_Passwd_Add(
in_Username varchar(255),
in_randomURLs text
)
RETURNS void AS $$
BEGIN
IF (SELECT Dugong.Users_isExist(in_Username)) THEN
INSERT INTO dugong.Forget_Passwd (Username, randomURLs, used)
VALUES (in_Username, in_randomURLs, FALSE);
ELSE
RAISE EXCEPTION USING ERRCODE = '20000', MESSAGE = 'Username not found';
END IF;
END;
$$ LANGUAGE PLPGSQL;
My Node Express with pg module will use client.query(). client.query() has callback err and result.
With my example in here. I can use err.message and err.code to get error message and error code respectively.
Question :
I want my code be able to RAISE any error from database side not restrict only my specific error code.
How can I do that?
You can use raise to throw both custom and standard exceptions.
Reference standard exceptions either by it's code:
raise sqlstate '22012';
or by name:
raise division_by_zero;
Here is the list of defined error codes and names; more information about raise: "Errors and messages".

How can I get the line number of a SyntaxError thrown by require(id) in node.js?

(source: nocookie.net)
I am trying to get access to the text I highlighted in red inside my nodejs program. I currently have a try/catch block around the require call, but the stack trace I dump in the catch does not contain the information I am trying to access (namely, the line number in 'testdebug.js' where the error occurred).
The lines highlighted in red are printed by something in node's internals, apparently. How can I store that string inside of my program? Code is below.
var syntaxError = true;
try {
debugModule = require('./testdebug.js')
syntaxError = false;
}
catch(e) {
console.log(e.stack);
//there was a syntax error.
}
This guy knows what's up. His module checks the code for parser errors using esprima, and gives a useful object for dissecting them.
https://github.com/substack/node-syntax-error

Resources