package com.xhkjedu.exception;
import com.alibaba.fastjson.JSON;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @创建人 :zj
 * @创建时间 2019/11/7
 * @修改人和其它信息
 * @描述 :项目异常处理类:
 * 项目中所有controller层抛出的异常信息都会被拦截。
 * 方便我们查看异常原因，减少开发中大量的try catch。
 * 拦截异常后，打印异常信息，返回前端约定参数对象。
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class ErrorAdivceController {
    @ExceptionHandler(MissingParametersException.class)
    public ResultVo missingParametersException(MissingParametersException ex) {
        log.error("参数异常:   -------> " + ex.getMessage());
        return new ResultVo(1, ex.getMessage());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResultVo DataIntegrityViolationException(DataIntegrityViolationException ex){
        log.error("数据库异常:   -------> " + ex.getMessage());
        String msg = ex.getMessage();
        if (N_Utils.isNotEmpty(msg) && msg.indexOf("SQLIntegrityConstraintViolationException") != -1){
            return new ResultVo(1,"存在关联信息");
        }
        return new ResultVo(1,"数据库处理异常");
    }

    @ExceptionHandler(Exception.class)
    public ResultVo exceptionHandler(Exception ex) {
        log.error("程序运行异常:   -------> " + ex.getMessage());
        String msg = ex.getMessage();
        if (N_Utils.isNotEmpty(msg) && msg.indexOf("JSON parse error") != -1){
            return new ResultVo(1,"json格式不对");
        } else if (N_Utils.isNotEmpty(msg) && msg.indexOf("Maximum upload size exceeded") != -1) {
            return new ResultVo(1, "文件过大");
        }
        return new ResultVo(1, "程序处理异常");
    }

    @ExceptionHandler(NullPointerException.class)
    public ResultVo nullPointerException(NullPointerException ex) {
        StackTraceElement element = ex.getStackTrace()[0];
        log.error("参数为空异常:   -------> " + JSON.toJSONString(element));
        return new ResultVo(1, "参数为空异常");
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResultVo illegalArgumentExceptionHandler(HttpServletRequest request,IllegalArgumentException ex) {
        log.error("请求参数错误 URL : {}，Exception : {}", request.getRequestURL(),ex.getMessage());
        return new ResultVo(1, "请求参数错误");
    }

    @ExceptionHandler(ServiceException.class)
    public ResultVo missingParametersException(ServiceException ex) {
        log.error("提示信息:   -------> {}", ex.getMessage());
        return new ResultVo(1, ex.getMessage());
    }


}
