package org.springframework.social.evernote.api;

import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;

/**
 * @author Tadaya Tsuyukubo
 */
public class EvernoteExceptionUtils {

	public static EvernoteException convert(Exception ex) {
		StringBuilder sb = new StringBuilder();
		sb.append(ex.getMessage());
		if (ex instanceof EDAMUserException) {
			sb.append(", ErrorCode [");
			sb.append(((EDAMUserException) ex).getErrorCode());
			sb.append("], Parameter [");
			sb.append(((EDAMUserException) ex).getParameter());
			sb.append("]");
		}
		if (ex instanceof EDAMSystemException) {
			sb.append(", ErrorCode [");
			sb.append(((EDAMSystemException) ex).getErrorCode());
			sb.append("], RateLimitDuration [");
			sb.append(((EDAMSystemException) ex).getRateLimitDuration());
			sb.append("]");
		}
		if (ex instanceof EDAMNotFoundException) {
			sb.append(", Identifier [");
			sb.append(((EDAMNotFoundException) ex).getIdentifier());
			sb.append("], Key [");
			sb.append(((EDAMNotFoundException) ex).getKey());
			sb.append("]");
		}
		return new EvernoteException(sb.toString(), ex);
	}

	public static <T> T wrap(Operation<T> operation) throws EvernoteException {
		try {
			return operation.execute();
		} catch (Exception ex) {
			throw convert(ex);
		}
	}

	public static interface Operation<T> {
		T execute() throws Exception;
	}
}

@@ -275,16 +275,136 @@
 tils %7B%0A%0A
+%09/**%0A%09 * convert to %7B@link EvernoteException%7D%0A%09 *%0A%09 * @param ex original exception%0A%09 * @return converted exception%0A%09 */%0A
 %09public 
@@ -1310,24 +1310,343 @@
 ), ex);%0A%09%7D%0A%0A
+%09/**%0A%09 * Execute the given operation and wrap the thrown exception to %7B@link EvernoteException%7D.%0A%09 *%0A%09 * @param operation a callback operation%0A%09 * @param %3CT%3E       operation return type%0A%09 * @return return from callback operation%0A%09 * @throws EvernoteException EvernoteException wrapping a thrown original exception%0A%09 */%0A
 %09public stat
@@ -1806,16 +1806,183 @@
 %09%09%7D%0A%09%7D%0A%0A
+%09/**%0A%09 * Callback interface for %7B@link EvernoteExceptionUtils#wrap(org.springframework.social.evernote.api.EvernoteExceptionUtils.Operation)%7D.%0A%09 *%0A%09 * @param %3CT%3E%0A%09 */%0A
 %09public 

add documentation