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) {
		// 如果是用户未登陆异常，那么不处理，向上抛出
		if (exception instanceof UserNotLoginException) {
			throw new UserNotLoginException();
		}
		ModelAndView andView = new ModelAndView();
		// 请求地址
		String url = request.getRequestURI();
		// 判断是前台请求还是后台请求
		if (url.indexOf("admin") != -1) {
			andView.setViewName("msg/error");
		} else {
			andView.setViewName("forward:/wechat/error");
		}
		// 错误日志
		fwLogger.error(this, url + ", error[" + exception.getMessage() + "]");
		exception.printStackTrace();
		// 返回逻辑视图
		return andView;
	}
}
