package com.leanwo.activiti.exception;

import java.io.UnsupportedEncodingException;

import org.springframework.web.client.HttpServerErrorException;

/**
 * 异常转换器
 * @author YangZhiJie
 *
 */
public class ExceptionParse {
	
	/**
	 * 提取异常中包含的有用信息
	 * @param ex
	 * @return
	 */
	public static String parse(Exception ex) {
		if(ex instanceof HttpServerErrorException) {
			return parse((HttpServerErrorException)ex);
		}else if(ex.getCause() != null && ex.getCause() instanceof HttpServerErrorException) {
			return parse((HttpServerErrorException)ex.getCause());
		}else {
			return ex.getMessage();
		}
	}

	/**
	 * 提取异常中包含的有用信息
	 * @param ex HttpServerErrorException
	 * @return
	 */
	public static String parse(HttpServerErrorException ex) {
		byte[] datas = ex.getResponseBodyAsByteArray();
		String message = null;
		try {
			message = new String(datas,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//String message = ex.getResponseBodyAsString();
		return message;
	}
	
	public static ServerException getServerException(Exception ex) {
		if(ex instanceof ServerException) {
			return (ServerException)ex;
		}
		Throwable throwable = ex;
		while(throwable.getCause() != null) {
			if(throwable.getCause() instanceof ServerException) {
				return (ServerException) throwable.getCause();
			}
			throwable = throwable.getCause();
		}
		
		return null;
	}
}
