package com.yeejoin.amos.boot.module.hygf.api.config;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * @description: 全局异常处理器
 * @author: duanwei
 * @create: 2019-08-28 20:07
 **/
@RestControllerAdvice
@Slf4j
@Primary
public class GlobalExceptionHandler {

	@Value("${exception.debug:false}")
	private boolean debug;

	/**
	 * 校验异常统一拦截地方
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ Exception.class })
	@ResponseBody
	public ResponseModel<Object> handleException(Exception e) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		ResponseModel<Object> response = new ResponseModel<>();
		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		response.setTraceId(RequestContext.getTraceId());
		response.setPath(request.getServletPath());
		if (debug) {
			// 获取异常的堆栈跟踪信息
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			String stackTrace = sw.toString();
			response.setDevMessage(stackTrace);
			response.setMessage(stackTrace);
			System.err.println(e.getMessage());
			log.debug("Exception stack trace (debug mode): {}", stackTrace);
		} else {
			response.setDevMessage(e.getMessage());
			response.setMessage(e.getMessage());
		}
		return response;
	}

}