Exceptions in Lablgtk callbacks - exception

In Lablgtk, whenever there is an exception in a callback, the exception is automatically caught and an error message is printed in the console, such as:
(prog:12345) LablGTK-CRITICAL **: gtk_tree_model_foreach_func:
callback raised an exception
This gives no stack trace and no details about the exception, and because it is caught I cannot retrieve this information myself.
Can I enable more detailed logging information for this case? Or prevent the exception from being caught automatically?

I guess the best way to do so is to catch your exception manually and handle it yourself.
let callback_print_exn f () =
try f () with
e -> my_exn_printer e
Assuming val my_exn_printer : exn -> unit is your custom exception printer, you can simply print your callbacks exceptions by replacing ~callback:f by ~callback:(callback_print_exn f) in your code.
Of course, you can also with that method send that exception to another
thread, register a "callback id" that would be passed along with your exception...
About the stack trace, I'm not sure you can retrieve it easily. As it's launched as a callback, you probably want to know the signal used and that can be stored in your callback handler.

I had another similar issue, but this time it was harder to find where to put the calls to intercept the exception.
Fortunately, this time there was a very specific error message coming from the Glib C code:
GLib-CRITICAL **: Source ID ... was not found when attempting to remove it`
Stack Overflow + grep led me to the actual C function, but I could not find which of the several Lablgtk functions bound to this code was the culprit.
So I downloaded the Glib source, added an explicit segmentation fault to the code, compiled it and used LD_LIBRARY_PATH to force my modified Glib version to be loaded.
Then I ran the OCaml binary with gdb, and I got my stack trace, with the precise line number where the Lablgtk function was being called. And from there it was a quick 3-line patch.
Hacks like this one (which was still faster than trying to find where to intercept the call) could be avoided by having a "strict mode" preventing exceptions from being automatically caught. I still believe such a switch should be available for Lablgtk users, and hope it will eventually be available.

Related

Micronaut: Proper logging of "uncaught" Exceptions to not appear on System.err

I've a question regarding capture of "uncaught" exceptions, which appears with stack trace on System.err, circumventing logging configuration: All the other log messages appear properly formatted on System.out (JSON-formatted in my case). But this doesn't happen with Exceptions and stack traces "logged" to System.err!
I've recognized this to happen under at least two circumstances:
Asynchronous execution of tasks (HTTP requests in my case) via ExecutorService (as mentioned in "Scheduled Tasks" chapter). I've added #Retryable annotation to the method; but after all retries fail, "final" Exception thrown by last unsuccessful retry appears on System.err with its stack trace (the other ones thrown by earlier failed retries do not appear, seems they are caught by retry "mechanism" under the hood).
With Exceptions thrown by failed Health indicators (they are implemented by subclassing AbstractHealthIndicator).
I've tried implementing my own TaskExceptionHandler, replacing the default one (also mentioned in "Scheduled Tasks" chapter); and/or by adding System.setErr(System.out) in main method before building/setup of Micronaut Application Context. But nothing seems to help as my test cases attest.
Have I missed a chapter in Micronaut's documentation?
Thanks for any hints.
Regards
Christian
My wager is that Micronaut doesn't provide tools for setting a global uncaught exception handler because that's governed by the wider JRE. We've solved the problem in a few of our services with Thread.html#setDefaultUncaughtExceptionHandler by doing something like this at application startup:
Thread.setDefaultUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception", e));

Async exception not caught by debugger

I'm working on an MVC5 project in VS2013. I seem to be finding that most (but not all) of my exceptions are being ignored by the debugger and as a result I end up with the exception and stack trace simply being written to the browser, precluding any examination of the objects involved in the exception.
For instance - I deliberately code an exception to prove the point:
<Authorize(Roles:="IdentityAdmin")>
Public Async Function Import(model As RegisterViewModel) As Task(Of ActionResult)
Dim a As Object = "he"
Dim b As Integer = a
Clearly the last line will throw a 'type mismatch' exception which I think should result in the debugger halting execution, highlighting the error in the VS2013 UI to enable me to examine the various objects and determine the problem.
Instead I simply find myself with the browser detailing the exception and VS2013 unresponsive:
Server Error in '/' Application.
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a
correct format.
Source Error:
Line 291: If Db.Users.Find(acct.username) Is Nothing Then
Line 292: Dim a As Object = "he"
Line 293: Dim b As Integer = a
When I insert the same exception-generating code into a non-async part of the code the VS debugger does catch the exception - so I am guessing this is an issue with debugging async code. Is it really the case that the VS debugger can't catch these exceptions?
UPDATE
After further searching I came across a suggestion to disable 'Just My Code' and manually enable various types of exception. There was the expected hailstorm of First Chance Exceptions most of which I could tune out by disabling certain exceptions. But this DID 'fix' the behaviour described above. It seems that the debugger is regarding my child async threads as 'Not My Code'. Slightly baffled but I guess this could be an answer of sorts?
As per the update above, the problematic behaviour detailed in the question seems to be fixed by a combination of:
Turn off 'Just My Code' in the debugger options.
Enable certain classes of exceptions in Debug/Exceptions.. - in my case Common Language Runtime Exceptions and Managed Debugging Assistants seemed to ensure that the debugger caught all my exceptions (async or otherwise).
Disable thrown (but unremarkable) exceptions which cause most grief (wrong globalisation etc).
The last two stages were happened upon somewhat by trial and error and I suspect I should ultimately chase down most of these non-breaking exceptions when I clean the project up.
Disabling Just My Code should not make a difference in this case, enabling "Break when an exception is thrown" is what you want to make the debugger stop at the correct place.
The issue is that when you make the method Async, it runs in a background Task. The Task will catch any exceptions that occur in the code it is executing and re-throw that exception to whatever uses the result of the Task. So for example if you have the following MVC code
Async Function Index() As Task(Of ActionResult)
Dim n as Integer = Await Method1()
Return View()
End Function
Async Function Method1() As Task(Of Integer)
Dim a As Integer = 0
Dim b As Integer = 1 / b
Return b
End Function
The Task executing the code inside of Method1 will catch the exception, and throw it in Index since it is using the result of Method1, then the Task executing Index will catch that exception and re-throw it to the MVC framework code that is using the result of Index, and then the MVC framework handles the exception and displays the error page.
When Just My Code is enabled and methods are executing synchronously the debugger will stop when an exception propagates out of user code with the message that it was "user unhandled". In the case above if an exception propagates from Index to the MVC framework which is not your code, the debugger will stop when JMC is enabled. Since in the case of an asynchronous method the exception is not unhandled but caught by the Task, it does not cross out of user code so disabling Just My code will not make a difference.
The reverse of this is, if an exception occurs in your synchronous method and you have disabled Just My Code, the debugger would not stop anyway, because there is no notion of "User Unhandled" when JMC is disabled and the MVC framework will ultimately handle that exception.

How to get Clojure exception notification when they happen on the EDT?

I've just been scratching my hairs for a long time with an error I couldn't find. It turned out to be an arity exception but apparently because it happened on the EDT I couldn't "see" it. It didn't show in the "lein run" terminal when run from a terminal and it didn't show in any Emacs buffer when run from Emacs.
After a very long time I ended up doing this:
(try (function-call-with-arity-error ...) (catch Exception e (println e)
and, at last, thanks to this, I got to see this printed:
#<ArityException clojure.lang.ArityException: wrong number of args passed to...
and hence I've been able to find my error.
And if I do this:
(do
(println "trying...")
(arity-error-here-on-purpose) ; this ones throws the arity error
(println "done")
)
Then the terminal prints "trying..." but never gets to "done...".
I tried setting a default uncaught exception handler: the exception isn't getting caught. It's as if the program or the EDT was "stuck" after the arity exception (without printing anything anywhere).
How am I suppose to deal with this the next time? Because I couldn't see any message anywhere it took me a really long time to find. Once again: nothing in the 'lein run' terminal and nothing in any Emacs buffer.
Should I create a function that wraps calls that should happen on the EDT inside try / catch manually and that then logs/println the exception?
Also note that this is in a relatively "long" Clojure app: 1000 lines of code, so I can't paste it here and I couldn't reproduce that behavior in a short example (but it happens consistently in my app).
You can register an uncaught exception handler with a Thread so you don't have to wrap all the calls that can occur on the EDT.
Thread.UncaughtExceptionHandler
Try registering one with the EDT and seeing if this gives you the desired behavior.

Obtaining stack traces in ClojureScript

In my ClojureScript programs running in FireFox 5.0 on Ubuntu 10.04.1 LTS, I get a single cryptic line when an exception is thrown.
'Error: No protocol method ISeqable.-seq defined for type object: [object Object]' when calling method: [nsIDOMEventListener::handleEvent]
The "-seq" bit seems strange to me and I have searched the generated javascript files for it and not found it.
I hope I am not missing something entirely obvious, but how do I get a stack trace of the exception thrown? How are you debugging your scripts?
Unfortunately stack traces from errors rely on browser support. Most (all?) browsers will allow you to access a canned version of the stack trace (usually the top 10 elements, iirc) as a string by dereferencing the 'stack' field, so you could do something like this:
(try ...throws...
(catch js/Error e
(.log js/console (.-stack e))))
However, string stack traces aren't much fun, you can't click them to take you to the source. Better is printing the exception directory to the javascript console (if it's available) to print stack traces with clickable links. E.g.
(try ...throws...
(catch js/Error e
(.log js/console e)))
At least in chrome, this only works if the javascript console was open when the error was thrown. This is great for debugging, but less useful when the error was unexpected.
The javascript console objects provided by most browsers have lots of useful functions that you can use from clojurescript. If you want to get helpful line numbers though, you probably want to write a couple of macros to inject the code to print to the console, otherwise all your line numbers will point to your print function.
Looks like you are passing a Javascript object to a Clojurescript function which expects a Clojure sequence. Try (my-function (js->clj my-thing)) edit: or, I'm guessing you're using (.strobj) where you don't need to

How do I log a general exception to the Event Log?

I have a windows service, in which I want a top level try-catch that catches any otherwise unhandled (or bubbled) exception, logs it to the Event Log and then swallows it so the service keeps running. However, I can't find any overload to System.Diagnostics.EventLog.WriteEntry that takes an exception as a parameter - is there no way to just give the event log the exception and let it parse out the message on its own?
Unfortunately there is no standard way of just passing the Exception to the Eventlog, built in to the .NET framework.
To have an exception written to the EventLog with the smallest development effort, you would need to write something like:
EventLog myLog = new EventLog();
myLog.Source = "Your Source";
myLog.WriteEntry(exception.ToString(), EventLogEntryType.Error);
But normally you would try to do some formatting of your exception.