Php7 practices regarding Throwable errors - magento

Long story short is that we've recently switched from php 5.6 to php 7. Although the application (a Magento 1.9 based app) seems to work accordingly after the switch, we have some shell scripts which somehow/sometimes die all of the sudden without knowing why:
Mage::log("doing something", null, 'custom.log', true); <- logged, see it
doSomething(); <- perfroms a service call, which looks like it's done properly
Mage::log("something done", null, 'custom.log', true); <- not logged
The problem in the above is that we have absolutely no error, warning, etc. so we cannot determine what happens. Since the changing of error handling in Php7, I assume that an error occurs (which previously was being logged in /var/log/...) and now is thrown as an Error exception, which based on Php7 specifications is not caught by a classic catch(Exception $e){} block. So my main questions regarding this whole situation is:
When switching from Php5.X to Php7, wouldn't it be a good practice to change the catch(Exception $e) with catch(Throwable $e) as Throwable covers both Excptions and new Errors? Otherwise, if I'm correct, one should add multiple "catch (Error $e)" blocks inside the code where this could occur in order to catch these error now.

Related

Vs2019+vs2022 avoid breaking on Xamarin.Essentials.FeatureNotSupportedException

When using sensors such as barometer,compas etc. in Xamarin.Forms you cannot check if the sensor is available but have to try starting it and then catch the exception, if it is not there, such as here.
try
{
Barometer.Start(SensorSpeed.Game);
}
catch
{
//failed
}
The issue is that this happens every single time, I debug on a device without these sensors, and though I catch the exception, I break into it all the time.
The exception is
Xamarin.Essentials.FeatureNotSupportedException: 'Specified method is not supported.'
but when I, in exception settings, uncheck that one from "break when thrown", it still breaks on the exception.
This derives from
System.NotSupportedException
which i then also uncheck, and still it breaks on it.
The next levels up are
System.SystemException
System.Exception
which I can uncheck to stop breaking when thrown, but I would rather do that, since then everything is effectively not breaking if caught, which I would still like.

Is SmtpClient.SendAsync() really faster than SmtpClient.Send()

I was refactoring some of my code into a service and I was going to roll async all the way through down to my EmailService's Send() method.
I was about to replace Send() with SendAsync() and noticed the extra callback parameter.
Well decided to dig in and read about it a little more in depth here:
https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.sendasync?view=netcore-3.1#definition
I think this would be useful to set up logging to database on an error:
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
// TODO: Log error to DB
}
e.Cancel would never happen.
The only thing I would be concerned about is logging errors and message sent.
Because the example console program says message sent even though if I have say a port wrong and the message doesn't go through.
The only time it would report the error is for an ArgumentNullException or InvalidOperationException.
So logging message sent could be erroneous.
But there is no way to check for sure if a message goes since it returns void and not a success bool. I guess this is better than putting the Send() in a try/catch which would be more expensive.
One alternative is to setup the callback to an empty SendCompletedCallback() and just have this:
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Do nothing
}
Then we get the benefit of Async non blocking in our emails and have the infrastructure set up for a callback if we ever need it.
But we are not forced to add any funtionality at the moment.
Am I right in thinking this through here.
I think I am going with this approach.
I found the
SendMailAsync()
method works best.
You don't need a callback or a user token.
Easy to implement and non-blocking.

Function showing mysterious behaviors

I am developing an android application with kotlin assistance but the question is based on pure kotlin fundamentals. Below is the function which is showing some unusual behavior:
fun CatchThat(funct: () -> Unit){
try {
funct()
}catch (ex: Error){
ex.printStackTrace()
}
}
When I use it in my code
CatchThat {
// Proprietary Code goes in here
}
Debugger does not work properly(sometimes)
The proprietary code does not execute at all(sometimes)
Why is that behavior encountered or am I getting some concepts wrong(maybe lambdas). Any help or suggestions are heartily welcomed.(I am a tyro in kotlin)
EDIT The thing that I am doing in Proprietary code.
I am trying to invoke a Thread Pool that is in turn calling a web activity. This is the best and all I could explain about it. I am sorry for that.
try/catch will only work on the current thread. In your snippet, if some exception ocourrs in another thread, the try/catch won't work
For example:
try {
println("Hola mundo 1!")
println(5 / 0)
} catch (ex: Throwable) {
println("Oups! $ex")// will be printed
}
try {
Thread {
println("Hola mundo 2!")
println(5 / 0)
}.start()
} catch (ex: Throwable) {
println("Oups! $ex")// won't be printed
}
println("Hola mundo 3!")//The exception thrown in the external thread don't kill the current thread
For the debugging issues take a look to Android Studio threaded debugging
I am not sure if it sorts out the problem but it's just worth a try since all your efforts went in vein(and also because there is no error in your syntax).
I guess if debugger stops on wrong line(or sometimes doesn't work), it usually means that
something broken in the code cache .
Try invalidating Idea cache and restarting if you are using Idea of course.
And before doing that
I would also recommend to update Kotlin with the latest version.

Is it possible to add additional information for crashes handled by Xamarin.Insights analytics framework

I have an xamarin.android with xamarin.insights intergrated.
Right now every time I handle error manually (try/catch) I'm adding information about environment (staging/production):
try
{
ExceptionThrowingFunction();
}
catch (Exception exception)
{
exception.Data["Environment"] = "staging";
throw;
}
But this information is missing in case if error handled by xamarin.insights itself (in case of crash).
It is possible to add additional exception data in case of crash?
docs reference I used
From reading the docs page reference that you mentioned, I still get the impression that you have to call the .Report method as well as in:-
Insights.Report(exception, new Dictionary <string, string> {
{"Some additional info", "foobar"}
});
What I believe they are saying in this example:-
try {
ExceptionThrowingFunction();
}
catch (Exception exception) {
exception.Data["AccountType"] = "standard";
throw;
}
Is that you have the ability when any Exception is encountered, to package additional information that you can later send to the Insights server, as the Data property of the Exception is just a Key/Value Dictionary.
So if you had an Exception several layers deep, you can choose to re-throw the Exception with additional information contained within it that you will later send to the Insights server.
At a higher level, you can then take the Exception that was thrown deeper down the call-hierarchy and then call the Insights.Report, with:-
Insights.Report(
{the rethrown exception in your higher up try..catch block},
{rethrown exception}.Data
);
that will then send all the additional Key/Value information previously captured.
From seeing your last part of your question though it looks like you are interested in Insights handling and sending this additional .Data automatically should there be an unhandled exception.
If it is not currently being sent, then perhaps suggest to them that this can be sent also? As it sounds a feasible request for this to automatically be sent as well incase of an unhandled exception.
Update 1:-
Yes - I understand about the unhandled exception scenario now that you are referring to.
I have not dealt with this component directly, so there may be hooks / event handlers or something already defined where you can tap into this, and execute some custom code just prior to this being sent.
If this is not available, then perhaps suggest this to them to include as its a Beta product?
Alternatively, you could still achieve this yourself by capturing the unhandled exceptions just prior to them falling. You'd have to code this however on each platform.
For instance on Windows Phone in the App class there is Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) to which you could then supplement the Exception thrown with this extra .Data.
For Android you could take a look at this post that describes how to catch uncaughtException that will help you in capturing the unhandled exceptions.
Whether just supplementing the Exception in these handlers above is enough all depends on how they've written their hook into this, as to how well it behaves and whether it is executed first, prior to their implementation.
You will have to try and see if it does. If it doesn't behave well, allowing you to supplement extra data prior to the automatic call to Insights, you have another fallback solution, to just do the .Report call manually within these unhandled exception handlers yourself to make this work and supplement the extra .Data to achieve your aim.

Exception handling strategy

Imagine you have some code that could potentially throw an exception. For example, you try
to send an e-mail message to a mail server, or write a file to disk while you’re not sure if you have the right permissions to do so. What kind of exception handling strategy would you use to avoid the exception from being displayed in the browser? What code would you need?
All languages that can throw exceptions have some manner by which to catch them.
They often look something like this:
try
{
some_risky_thing();
}
catch(Exception e)
{
handle_the_exception();
}
By catching the exception you stop it's propagation up the call stack (where it will eventually find the user).
In order to stop all exceptions getting to the user put one of these at the very top level you have available. Then you can catch any stray exceptions you've missed and do something more appropriate than throw them at the user (like log them somewhere discretely).
It depends.
For those cases, I would probably wrap the code that can throw the exception in a try/catch block. Different languages call this construct something different - sometimes it's try/catch/finally, others it's try/except.
However, it's easy to abuse exceptions and exception handling. A few things that you need to avoid are using exception handling for flow control, handling exceptions too soon (keep passing them up the call stack until they can be appropriately handled), and treating non-exceptional conditions as exceptional.

Resources