package com.mortals.xhx.base.framework.exception;

import com.mortals.framework.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

/**
 * 统一异常处理
 */
@ControllerAdvice
public class ExceptionHandle {

	private final static Logger log = LoggerFactory.getLogger(ExceptionHandle.class);

	public static final String KEY_RESULT_CODE = "code";
	public static final String KEY_RESULT_MSG = "msg";
	public static final String KEY_RESULT_DATA = "data";
	public static final int VALUE_RESULT_FAILURE = -1;

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public String handle(Exception e) {
		JSONObject ret = new JSONObject();
		ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
		if (e instanceof AppException) {
			StackTraceElement stack = e.getStackTrace()[0];
			log.error("[business error]=========stack message[{}],[{},method:{},line{}][{}]", e.getMessage(),
					stack.getClassName(), stack.getMethodName(), stack.getLineNumber(), e.getClass().getName());
			AppException ex = (AppException) e;
			ret.put(KEY_RESULT_MSG, ex.getMessage());
		} else {
			log.error("[system error]{}", e);
			ret.put(KEY_RESULT_MSG, "unknown exception!");
		}
		return ret.toJSONString();
	}
}
