package com.dcit.danger.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
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;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.exceptions.TemplateInputException;

import com.dcit.common.enums.ResultEnum;
import com.dcit.common.utils.ResultVOUtil;
import com.dcit.common.vo.ResultVO;
import com.dcit.danger.exception.IOCException;

import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
public class IOCExceptionHandler {

	@ResponseBody
	@ExceptionHandler(value = IOCException.class)
	public ResultVO<Object> defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, IOCException exception)
			throws Exception {
		log.error("【IOC系统异常】异常信息={}",exception.getMessage());
		return ResultVOUtil.error(exception.getCode(), exception.getMessage());
	}
	
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public ResultVO<Object> defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception exception)
			throws Exception {
		log.error("【Exception系统异常】异常信息={}",exception.getMessage());
		return ResultVOUtil.error(ResultEnum.OPERATION_FAIL, exception.getMessage());
	}
	
	
	/* *
     * @Description 拦截操作数据库异常
     * @Param [e]
     */
    /*@ExceptionHandler(DataAccessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultVO<Object> sqlException(HttpServletRequest request, HttpServletResponse response, DataAccessException e) {
        log.error("【DataAccessException异常】数据操作异常,e={}",e.getMessage());
        final Throwable cause = e.getCause();
        // 之后判断cause类型进一步记录日志处理
        if (cause instanceof MySQLIntegrityConstraintViolationException ) {
            return ResultVOUtil.error(ResultEnum.SERVER_FAIL);
        }
        return ResultVOUtil.error(ResultEnum.SERVER_FAIL.getCode(),e.getMessage());
    }*/
	

	@ExceptionHandler(value = TemplateInputException.class)
	public ModelAndView templateInputErrorHandler()
			throws Exception {
		log.error("【TemplateInputException系统异常】");
		return new ModelAndView("error");
	}

}
