package com.cku.util;

import com.cku.core.ZAErrorCode;
import com.cku.core.RetryException;

public class RetryUtils
{
	public static <T> T CallWithRetry(IRetryFunction<Object[], T> f, int times, Object... params) throws Exception
	{
		Debugger.doAssert(times > 0, ZAErrorCode.ZA_ERC_INVALID_PARAMETER, "Invalid retry call");
		
		int current = 0;
		Exception lastException = null;
		while (current < times)
		{
			try
			{
				T result = f.execute(params);
				return result;
			}
			catch (Exception e)
			{
				if (e instanceof RetryException)
				{
					RetryException r = (RetryException)e;
					lastException = r.getException();
					current++;
					continue;
				}
				else
				{
					throw e;
				}
			}
		}
		
		throw lastException;
	}
}
