I need to print some exception onto screen/Log in file.
Is there a way to get all exceptions that resulted from last script execution only ?
Consider this as an example :
I open a powershell window
I exceute abc.ps1 , it throws some error.
I execute now xyz.ps1 which throws more than one exception. Now I want to log all exception from xyz.ps1 only.
If i use $error[0], I get only last exception . I need other exceptions that were thrown by xyz.ps1 as well
I think I have come up with the way to do this. If you inspect the properties of $error[0] with Get-Member cmdlet ($error[0] | Get-Member) you should notice a property called ScriptStackTrace. This property tells us if the error was raised from a script or from console. With the following code I managed to achieve what you ask for:
for ($i=0;$i -lt $error.Count; $i++)
{ if ($Error[$i].ScriptStackTrace -match "xyz.ps1")
{ $error[$i] | out-file -Append "ErrorsScriptXYZ.txt" } }
If you intend to use the script in a callable way, add this as the last line of execution. Note that it will not catch terminating errors that could occur before the script operates. Explore the Get-Member cmdlet for more properties that you wish to manipulate on. Note that this will only search for errors in the current variable session, as the errors are gone on the next startup.
Related
The -errorline element of the return options dictionary for the following TCL script is "2":
puts [info patchlevel]
try {
error "this is an error"
} trap {} {result ropts} {
puts $result
puts $ropts
}
How do I get the stacktrace to display the line number in the source file where the error was actually raised (ie. line 4 instead of 2) ?
Example screenshot:
Tcl often has that information available, but doesn't use it.
It has the information available because you have a chance to retrieve it with info frame and getbytecode (which is in the tcl::unsupported namespace, mostly because we reserve the right to change how the bytecodes themselves work at any time). I'm not quite sure if that would work in your specific case, but if you put your test code in a procedure then it definitely would. (There are complexities here with fragility that I don't fully understand.)
It doesn't use it because, for backward-compatibility with existing tooling, it uses the line numbers it was using prior to the creation of the machinery to support info frame. Those line numbers are relative to the local script fragment (which is whatever reports the line number in the error info trace first); in this case, that is the body of the try.
I don't like that it works like that at all. However, changing things is a bit tricky because we'd need to also figure out what else to report and what to do in the cases where the information genuinely isn't available (such as for automatically-generated code where things are assembled from many strings from many lines).
I'm making a custom plugin to query a database for user info to aide customer support. My backend is slack.
Everytime I start the bot command I'm greeted with:
Computer says nooo. See logs for details:
catching classes that do not inherit from BaseException is not allowed
I'm not sure if this is warning me that I'm attempting to catch an exception that isn't a BaseClass in my code or if an unknown exception was raised and caught elsewhere outside of my plugin.
To debug I tried:
try:
do_the_thing()
except (TypeError, ValueError) as e:
return('Something went wrong.')
I also tried:
try:
do_the_thing()
except Exception as e:
return('Something went wrong.')
And I still get the errbot admonition. Note that the command still runs and does the right thing where there is no exception raised by do_the_thing().
It means that:
Somewhere in your code you have an except ... statement where the exception ... (or one of the exceptions in the sequence ...) is not a subclass of BaseException, and
An exception is being thrown that is caught by that except ... statement.
The TypeError can be raised only when an exception is actually thrown because the names you give to except ... must be evaluated for their current values at that time; just because TypeError referenced a particular class at one point in the program's execution doesn't mean it won't be changed later to reference another object (though that would be admittedly perverse).
The Python interpreter should be giving you a full traceback of the exception; the first thing you need to do is find this. It could be occurring in one of two situations. (This is for single-threaded programs; I'm assuming your program is not multithreaded.)
During the execution of your program, in which case the program will be terminated by the exception, or
During finalization of objects (in their __del__(self) functions) in which case the error will be printed to stderr.
In both cases there should be a stack trace, not just the error message; I've confirmed that at least on Python ≥3.4 a stack trace is printed out for case 2.
You then need to follow this stack trace to see where the problem lies. Remember that the names you give to except ... are variables (even things like TypeError) that can be reassigned, so that you could conceivably be dealing with a (perverse) situation like:
TypeError = False
try:
...
except TypeError:
...
But more likely it will be something obvious such as:
class MyException: # Doesn't inherit from Exception
...
try:
...
except MyException:
...
There is one special case you need to be aware of: if you are seeing messages to stderr (case "2. During finalization," above) printed out as your program exits that means that the exception was thrown during cleanup as the interpreter shuts down, where random variables throughout the program may have already been set to None as part of the cleanup process. But in this case your program should still exit successfully.
Is there any way to catch the global "Tcl Interpreter Error"? For example I would like to automatically store in some file the message that follows.
The core command for trapping any kind of error thrown by Tcl is catch. It takes at least one argument, a script to evaluate, and returns the result code from evaluating that script. The result code is 1 when an error occurs, 0 when there was no error, and a bunch of other things in other cases (indicating other types of usually-non-error exception). The catch also takes an optional argument that names a variable into which to write the result of evaluating the script or the error message. The global variable errorInfo will contain the stack trace in the case of an error (or from 8.5 onwards you can get the interpreter state dictionary with a further variable name passed to catch).
To trap an error in some script “foo.tcl”, you would use code like this:
if {[catch {source foo.tcl} msg]} {
puts "I got an error: $msg"
puts "The stack trace was this:\n$errorInfo"
}
It's up to you to work out how to write that out to a file if you want. (I use this technique with an outer script that implements a carefully tested error trap and which loads an inner script that does the real work. I find it works well. Or you can call procedures in that “caught” script. Up to you really; Tcl should make all errors trappable, and there are very few conditions which slip through.)
The other route that errors can be reported is via bgerror, which is called to handle errors that occur during event processing. It's a procedure you can write your own version of; it will be given a single argument when called that is the error message, and will have the global errorInfo set correctly when called:
proc bgerror {msg} {
global errorInfo
puts "I got an error in an event: $msg"
puts "The stack trace was this:\n$errorInfo"
}
If there is no implementation of bgerror defined, the stack trace is just written to the stderr channel. If you're using the Tk package, an implementation of bgerror is provided which pops up a dialog box describing the problem.
Try the bgerror or interp bgerror commands.
Read the bgerror documentation, it has a simple example.
I'm using XML::LibXML to parse a document.
The HTML file behind it, has some minor errors, and the parser reports them:
http://is.gd/create.php?longurl=http://google.com:15: validity error : ID smallink already defined
nal URL was http://google.com<span id="smallink"
^
http://is.gd/create.php?longurl=http://google.com:15: validity error : ID smallink already defined
and use http://is.gd/fNqtL-<span id="smallink"
^
However, I disabled error reporting:
my $parser = XML::LibXML->new();
$parser->set_options({ recover => 2,
validation => 0,
suppress_errors => 1,
suppress_warnings => 1,
pedantic_parser => 0,
load_ext_dtd => 0, });
my $doc = $parser->parse_html_file("http://is.gd/create.php?longurl=$url");
My only option to suppress those errors, is to run the script with 2>/dev/null, which I don't want. Could someone help me please get rid of those errors?
I have no idea if you're asking XML::LibXML corretly to not print its warnings. I'll assume you are and this is a bug in XML::LibXML (which you should also report to the author), and only address how to suppress warnings.
Every time a warning is about to be printed, perl will look up the value of $SIG{__WARN__} and, if that contains a code reference, invoke it instead of printing the warning itself.
You can use that stop the warnings you want to ignore to be printed to STDERR. However, you should be careful with this. Make sure to only suppress false-positives, not all warnings. Warnings are usually useful. Also, make sure to localize your use of $SIG{__WARN__} to the smallest possible scope to avoid odd side effects.
# warnings happen just as always
my $parser = ...;
$parser->set_options(...);
{ # in this scope we filter some warnings
local $SIG{__WARN__} = sub {
my ($warning) = #_;
print STDERR $warning if $warning !~ /validity error/;
};
$parser->parse_html_file(...);
}
# more code, now the warnings are back to normal again
Also note that this is all assuming those warnings come from perl-space. It's quite possible that libxml2, the C library XML::LibXML uses under the hood, writes warnings directly to stderr itself. $SIG{__WARN__} will not be able to prevent it from doing that.
A possible solution is to install a $SIG{__WARN__} handler which filters the messages or just silences all warnings:
local $SIG{__WARN__} = sub { /* $_[0] is the message */ };
Further to my adventures with Erlang and ErlyDB. I am attempting to get ErlyDB working with BeepBeep
My ErlyDB setup works correctly when run outside of the BeepBeep environment (see Debugging ErlyDB and MySQL). I have basically take the working code and attempted to get it running inside BeepBeep.
I have the following code in my controller:
handle_request("index",[]) ->
erlydb:start(mysql,Database),
erlydb:code_gen(["thing.erl"],mysql),
NewThing = thing:new_with([{name, "name"},{value, "value"}]),
thing:save(NewThing),
{render,"home/index.html",[{data,"Hello World!"}]};
When I call the URL, the response outputs "Server Error".
There is no other error or exception information reported.
I have tried wrapping the call in try/catch to see if there is an underlying error - there is definitely an exception at the call to thing:new_with(), but no further information is available.
The stacktrace reports:
{thing,new,[["name","value"]]}
{home_controller,create,1}
{home_controller,handle_request,3}
{beepbeep,process_request,4}
{test_web,loop,1}
{mochiweb_http,headers,4}
{proc_lib,init_p_do_apply,3}
Use pattern matching to assert that things work up to the call to thing:new/1:
ok = erlydb:start(mysql,Database),
ok = erlydb:code_gen(["thing.erl"],mysql),
You include only the stack trace, look at the exception message as well. I suspect that the error is that you get an 'undef' exception. But check that it is so. The first line in the stack trace indicates that it is a problem with calling thing:new/1 with ["name", "value"] as argument.
It is slightly odd that you show one clause of handle_request that is not calling home_controller:create/1 as per {home_controller,create,1} in the stack-trace. What do the other clauses in your handle_request/2 function look like?