package com.zcloud.util.examUntil;

/**
 * 说明：TODO
 * 作者：wangxuan
 * 官网：www.zcloudchina.com
 */


import com.zcloud.util.ReturnMap;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

import static com.zcloud.util.examUntil.CodeMessageEnum.SERVER_BUSY;


/**
 *  全局异常
 */
@RestControllerAdvice(annotations  = {ErrorOperation.class})
//@Slf4j
public class GlobalExceptionHandler {

    /**
     * 业务异常类
     *
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ReturnMap bizExceptionHandler(HttpServletRequest req, BizException e) {
        e.printStackTrace();
//        log.error("发生业务异常: {}, 请求接口: {}", e.getMessage(), req.getRequestURI());
        return ReturnMap.error("2001" ,e.getMessage(), req.getRequestURI());
    }


    /**
     * 空指针异常
     *
     * @param e 异常信息
     * @param req 请求
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ReturnMap exceptionHandler(HttpServletRequest req, NullPointerException e) {
        e.printStackTrace();
//        log.error("空指针异常信息: {}, 请求接口: {}", e, req.getRequestURI());
        return ReturnMap.error(SERVER_BUSY, req.getRequestURI());
    }

    /**
     * 接口请求方法异常
     *
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ReturnMap methodNotSupportedExceptionHandler(HttpServletRequest req, Exception e) {
        e.printStackTrace();
//        log.error("请求方法异常信息: {}，请求接口: {}", e, req.getRequestURI());
        return ReturnMap.error(SERVER_BUSY, req.getRequestURI());
    }

    /**
     * SQL 语法错误异常
     */
    @ExceptionHandler(value = MyBatisSystemException.class)
    @ResponseBody
    public ReturnMap sqlSyntaxErrorExceptionHandler(HttpServletRequest req, Exception e) {
        e.printStackTrace();
//        log.error("MyBatis系统异常信息: {}，请求接口: {}", e, req.getRequestURI());
        return ReturnMap.error(SERVER_BUSY, req.getRequestURI());
    }



    /**
     * 其他异常信息
     *
     * @param req
     * @param e
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ReturnMap exceptionHandler(HttpServletRequest req, Exception e) {
        e.printStackTrace();
//        log.error("未知异常: {}, 请求接口: {}", e, req.getRequestURI());
        return ReturnMap.error(SERVER_BUSY, req.getRequestURI());
    }
}
