How do I trap errors in Unity JavaScript?
What do you mean by trapping errors?
try/catch.
If you are talking about a “break point” as I know it, because I worked in Visual Studios most of the time before working in Unity, then I would like to know as well. All I know is that you can pause the game at any time and check values, edit them and resume playing your game. As far as stopping the game when you hit a certain line of code, I am not aware that exists.
No, I’m talking about detecting errors during runtime and trapping them so they don’t crash my game.
for example:
class SomeJsonClass {
var property : String;
}
function SomeFunction() {
var url : String = "http://someurl.com";
var www : WWW;
try {
www = new WWW(url);
}
catch (err) { // THIS LINE CAUSES A COMPILER ERROR
Debug.LogError("Error opening URL!");
return;
}
yield www;
try {
var response : SomeJsonClass = eval([url]www.data[/url]);
Debug.Log("object retrieved: " + response);
}
catch (err) { // THIS LINE CAUSES A COMPILER ERROR
Debug.LogError("Error parsing response!");
}
}
This script gives me an “Internal compiler error: Object reference not set to an instance of an object” on line 13
What is “err”? It isn’t referenced and that may be the reason why for the problems. Also, I’ve never used try/catch before.
It’s a declaration (of a variable of type System.Exception), not a reference. Not a problem, although it would be good to actually use it:
Debug.LogError("Error parsing response: " + err.Message);
With Javascript, you can’t use try/catch and yield in the same function, not in Unity 2.6 anyway.
–Eric
Really? Interesting. So there’s no way to trap for connection errors in the WWW object?
the object not an instance error comes from your declaration line.
try … catch will create a new subcontext so all assignements in there are not known outside unless the block didn’t fail so the compiler will throw the error.
for all objects assigned in a try block, you need to make sure that you at least initialize them through = null. this is what it throws at you on line 13
this is also the case in C# btw
No, this does not work. I still get the same “Object not initialized” error.
Eric was correct: the problem is that “try/catch” and “yield” cannot be in the same method. When I remove the yield statement, the script compiles fine.