package com.uas.eis.exception;

import javax.servlet.http.HttpServletRequest;
import com.uas.eis.entity.ErrorMsg;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionHandlerAdvice {

	private final static Logger logger = Logger.getLogger(ExceptionHandlerAdvice.class);
	
	/**
	 * 处理未被发现处理的运行时抛出异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ModelMap handleUnexpectedServerError(RuntimeException ex, HttpServletRequest request) {
		logger.error("error",ex);

		ModelMap map = new ModelMap();
		ex.printStackTrace();
		map.put("errCode", -1);
		map.put("errMsg", "server error");
		map.put("errDesc",ex.getMessage());
		return map;
	}
	
	/**
	 * 处理通过BaseUtil.showError抛出的异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(SystemException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ModelMap handleSystemError(SystemException ex, HttpServletRequest request) {
		logger.error("error",ex);

		ModelMap map = new ModelMap();
		ErrorMsg errorMsg = ex.getErrorMsg();
		map.put("errCode", errorMsg.getErrCode());
		map.put("errMsg", errorMsg.getErrMsg());
		map.put("errDesc",errorMsg.getErrDesc());
		return map;
	}
}
