Why Try Catch dont working on VideoPlayer Prepare() method? - unity3d

I want to catch an exception when the url for VideoPlayer is broken, but try{}catch{} didn't catch this exeption.
VideoPlayer cannot play url : http://migration.com:8080/video/test.mp4
Cannot read file.
My method
public async void Initialize(string url){
errorText.text = string.Empty;
_videoPlayer.url = "http://migration.com:8080/video/test.mp4";
_videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
_videoPlayer.targetTexture = rendererTexture;
_videoPlayer.errorReceived += OnPlayerErrorReceived;
try{
_videoPlayer.Prepare();
while (!_videoPlayer.isPrepared)
await UniTask.Yield();
}
catch{}
}
Has anyone solved this problem

What you see in the console is not the result of an actual Exception that is thrown and could be handled by the try - catch.
Unity rather already internally handled this and only prints a Debug.LogError / Debug.LogException for this
=> There is nothing actually thrown you can catch here.

Related

Flutter can't catch errors

In my Flutter app I can't get the try/catch part to work properly.
Future<void> getTime() async {
try {
Response response = await get(Uri.parse('https://api.api-ninjas.com/v1/worldtime?city=$location'),
// provoke an error
headers: {'Api_Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'},
);
Map data = jsonDecode(response.body);
time = "${data['hour']}h - ${data['minute']}m - ${data['second']}s";
}
catch (e) {
print('caught error: $e');
time = 'could not get time data';
}
}
It looks like the catch section is not reached.
Any idea ?
I guess the issue here is that try-catch blocks do not play well with async operations, in order to be able to catch errors in that context please refer to runZonedGuarded, it will encapsulate all method calls and listen to any exception thrown + handle them in a way just like catch does

Flutter: keep Stacktrace of an error with try catch

myCrashingFunc() {
var a = [];
print(a[0]);
}
try {
myCrashingFunc()
} catch (e) {
print(StackTrace.current.toString());
}
Actually, when I debug, I let everything crash so my StackTrace get me to the crashing line.
When I send my app in prod, I use try catch so new errors have default behavior handle.
Problem: with try catch, my Stacktrace stop in the catch, I would like to see the StackTrace give me insigh of the try. (ex: here my StackTrace will only go to the line print(StackTrace.current.toString());
Question: How can I get StackTrace of the function in the try. (ex: hre I would like to see my StackTrace go to line print(a[0]);)
You can access the stacktrace if you pass it as the second argument to catch as follows:
myCrashingFunc() {
var a = [];
print(a[0]);
}
try {
myCrashingFunc()
} on Exception catch (e, s) {
print(s);
}

How to avoid connection errors to an api in flutter? (breakpoint type appears in VS code)

I am purposely causing this error.
var response = await http.post(url,headers: {"Content-Type": "application/x-www-form-urlencoded"},body: args); //die here
//not continues
print(response);
I have turned off the execution of my server, so the web request cannot be executed. I want to know how I can control this error, since the application dies at this point.
how can I do it?
To catch an exception, you need to wrap the line that causes it with a try/catch block :
try {
var response = http.post(url);
}
catch(exception){
print(exception);
}

Flutter and Dart try catch—catch does not fire

Given the shortcode example below:
...
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} on Exception catch (_) {
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
I would expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch nor the continuation code fires...
flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
What am I missing here?
Functions can throw anything, even things that aren't an Exception:
void foo() {
throw 42;
}
But the on Exception clause means that you are specifically catching only subclass of Exception.
As such, in the following code:
try {
throw 42;
} on Exception catch (_) {
print('never reached');
}
the on Exception will never be reached.
It is not a syntax error to have on Exception catch as someone else answered. However you need to be aware that the catch will not be triggered unless the error being thrown is of type Exception.
If you want to find out the exact type of the error you are getting, remove on Exception so that all errors are caught, put a breakpoint within the catch and check the type of the error. You can also use code similar to the following, if you want to do something for Exceptions, and something else for errors of all other types:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Use:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
The rule is that exception handling should be from detailed exceptions to general exceptions in order to make the operation to fall in the proper catch block and give you more information about the error, like catch blocks in the following method:
Future<int> updateUserById(int userIdForUpdate, String newName) async {
final db = await database;
try {
int code = await db.update('tbl_user', {'name': newName},
whereArgs: [userIdForUpdate], where: "id = ?");
return code;
}
on DatabaseException catch(de) {
print(de);
return 2;
}
on FormatException catch(fe) {
print(fe);
return 2;
}
on Exception catch(e) {
print(e);
return 2;
}
}
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} catch (_) { . // <-- removing the on Exception clause
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
This works, but what is the rationale behind this? Isn't the type inconsistency an Exception?
As everybody or most of the people said, try to know exactly what error you are getting:
try{
}
catch(err){
print(err.runTimeType);
}
runTimeType will give you the type of data or exception you are getting or to put simple the exception itself.
And then do whatever you want. (Like if you are not getting the exception of what you expected, then try to fix that issue or change the exception.)
Another option is to go with general form.
Using the simple catch which will prompt every time.
The other possible reason for the catch bloc not to fire, as pointed out in this question, is missing brackets when throwing an exception.
Must write throw FormatException() instead of throw FormatException.
I had a issue with try catch but my problem was the API that I send http request, doesn't response of my request so that is why my request doesn't response anything and try catch didn't catch the error. So I suggest you to add timeout to your request so that if your api doesn't response your request after a while you can cancel your request with timeout. Here is an example how to use it;
try {
final response = await http.post(Url).timeout(Duration(seconds: 5));
} catch (error) {
print(error)
}

How to catch FacebookApiExceptions when using FacebookApp.ApiAsync in WP7?

I'm currently using Facebook C# SDK v4.2.1 and I'm trying to post something onto the user wall. It worked fine until I got an FacebookOAuthException (OAuthException) Error validating access token. error and I can't catch that exception and it crashes my app.
I'm using this call FacebookApp.ApiAsync("/me/feed", ...). Because it happens async I'm not sure where I have to put my try-catch block to catch that error but with no success
This is what I'm using:
private void shareFBButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
// ... code for preparing strings to post ...
try
{
// setup FacebookApp and params ...
app.ApiAsync("/me/feed", args, HttpMethod.Post, (o) => {
if (o.Error != null)
{
Debug.WriteLine("ERROR sharing on Facebook: " + o.Error.Message);
}
else
{
Debug.WriteLine("FB post success!");
}
}, null);
}
catch (Exception ex)
{
Debug.WriteLine("ERROR sharing on Facebook: " + ex.Message);
}
}
So can someone tell me where I have to put my try-catch block, so I can catch the OAuthException?
EDIT:
After further investigation, the FacebookOAuthExcpetion is thrown from Facebook C# SDK after the SDK catches WebException and FacebookApiException. For further information look at "Pavel Surmenok" his answer. That is exactly what is happening.
As of the moment the only solution for catching FacebookApiException (base class of all Facebook SDK exceptions) is to catch it in App.UnhandledException method. Check type of e.ExceptionObject and if it is a FacebookApiException set e.Handled to true and the app won't exit itself anymore.
I found a solution for my problem. Maybe I should rephrase my question.
"How to catch an exception which occurred on a background thread?"
Which is exactly what is happening in my original question. An exception is throw inside the Facebook C# SDK on a background thread because Api calls are executed asynchronously.
Maybe most of you already know this, but I didn't because I'm new to WP7 development.
Solution:
In App.UnhandledException event handler, just set the e.Handled flag to true. Then the app won't exit ifself.
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// catch Facebook API exceptions
// if handled is set to true, app won't exit
if (e.ExceptionObject is FacebookApiException)
{
e.Handled = true;
// notify user of error ...
return;
}
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
Not sure if this is the right way to catch an API exception, but works fine for now.
I've reproduced this trouble. As I can see, the exception is generated in FacebookApp.ResponseCallback method. It contains "try" block with two "catch" sections (one for FacebookApiException and one for WebException). In the end of each "catch" sections the exception is being rethrown and is never been handled (that's why your app crashes). So, the debugger says you about this (rethrown) exception.
Later in "finally" section they create FacebookAsyncResult with reference to this exception in the property "Error".
I think that your solution (to handle this exception in App.UnhandledException) is the most appropriate one.
By the way, it's interesting, why SDK developers decided to rethrow exceptions in FacebookApp.ResponseCallback.
The debugger usually does a good job of indicating where the exception came from. In the debugger, you can examine the exception details and look at the nessted InnerExceptions to find the root cause.
That said, if the exception is thrown from within the app.ApiAsync call, then the catch handler that you already have would catch any exceptions. By the looks of things in the SDK (I've only looked briefly), there are certain circumstances where exceptions are caught and forwarded to the callback in the Error property, which you are also checking.
By looking at the SDK code, it would seem that the exception being thrown is actually the FacebookOAuthException; is that the case? If that is the case, then it looks like this exception is never provided to the callback, but always thrown.
If you can give more details about exactly what the exception type is and where it's thrown/caught, I might be able to give a more useful answer.
Trying to catch the exception in App.UnhandledException does not work as it is on a different thread. But you can play with the 'error reason' property from authResult before doing the query and so you will avoid to have the exception thrown.
private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookAuthenticationResult authResult;
if (FacebookAuthenticationResult.TryParse(e.Uri, out authResult))
{
if (authResult.ErrorReason == "user_denied")
{
// do something.
}
else
{
fbApp.Session = authResult.ToSession();
loginSucceeded();
}
}