Is there a way to catch errors from coroutines?
You can’t place a Yield statement in a try/catch block, and if you place the StartCoroutine call inside a try/catch block, the runtime will probably have exited the block by the time the error occurs, causing the error to be unhandled.
Is it possible to hook into some sort of OnError event at a high level?
(FYI, I’m developing on Windows for a WebGL build)
Any thoughts would be appreciated and will probably make my code better.
Cheers
Peter
1 Like
I don’t think there’s a global way to do it except make your own little wrapper, something like:
EDIT: I’m gonna make a disclaimer, I just sort of off-the-cuffed that one… I think I have the correct termination logic propagated up? But if anyone suggests otherwise I’m open to the feedback as it is too late to do that tonight!
public static class CoRoWrapper
{
public static IEnumerator Wrap( IEnumerator ie)
{
while(true)
{
yield return ie.Current;
try
{
ie.MoveNext();
}
catch( System.Exception e)
{
UnityEngine.Debug.Log( "Coro went south.");
}
}
}
}
I think that’s correct, here’s a quick tester… then just wrap the IEnumerator in there before handing that to StartCoroutine().
Mebbe something like this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BadCoro : MonoBehaviour
{
IEnumerator Booboo()
{
Debug.Log( "Start.");
yield return null;
Debug.Log( "Okay.");
yield return null;
throw new System.Exception( "Boom!");
// never get past here obviously!
yield return null;
Debug.Log( "Done.");
}
void Start()
{
// only enable one of these at a time or you'll be very perplexed
// unhosted / unwrapped
StartCoroutine( Booboo());
//hosted / wrapped
// StartCoroutine( CoRoWrapper.Wrap( Booboo()));
}
}
Run that, then switch to the “hosted” version (commented out in the Start() method) and see the wrapped output.
Thanks @Kurt-Dekker
Wrapping the MOVENEXT in the CATCH block instead of the YIELD RETURN. I’ll give it a try when at some point.
Cheers