package com.iamberry.wechat.handles.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.app.tool.log.RatFWLogger;

@ControllerAdvice
public class ExceptionHandlerAction {
	
	@Autowired
	private RatFWLogger fwLogger;

	public void setInLongLogger(RatFWLogger fwLogger) {
		this.fwLogger = fwLogger;
	}
	
	/**
	 * 在这个方法的入参中可以加入Exception 入参中不能传入Map,若希望吧异常现象传入到页面，需要使用ModelAndView作为返回值
	 * @return
	 */
	@ExceptionHandler({ Exception.class })
	public ModelAndView handlerArithmeticException(Exception exception,
			HttpServletRequest request) {
		ModelAndView andView = new ModelAndView();
		// 请求地址
		String url = request.getRequestURI();
		// 打印信息
		fwLogger.info(exception.getMessage());
		// 判断是前台请求还是后台请求
		if (url.indexOf("admin") != -1) {
			andView.setViewName("msg/error");
		} else {
			andView.setViewName("forward:/wechat/error");
		}
		// 错误日志
		try {
			StackTraceElement[] list = exception.getStackTrace();
			StringBuffer stringBuffer = new StringBuffer("-----------------\r\n异常为:" + request.getRequestURI());
			for (int i = 0; i < list.length; i++) {
				stringBuffer.append(exception.getStackTrace()[i].getClassName());
				stringBuffer.append(".");
				stringBuffer.append(exception.getStackTrace()[i].getMethodName());
				stringBuffer.append("报错,文件为:" + exception.getStackTrace()[i].getFileName());
				stringBuffer.append("中的第:" + exception.getStackTrace()[i].getLineNumber());
				stringBuffer.append("行\r\n");
			}
			stringBuffer.append("----------------\r\n");
			fwLogger.error(this, stringBuffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 返回逻辑视图
		return andView;
	}

}
