package com.blueland.handler;

import cn.hutool.core.exceptions.ValidateException;
import com.blueland.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

import static com.blueland.constant.ResponseConstant.*;

/**
 * @author BigTian
 * @Description 异常统一处理类
 * @Date 2021/10/20 10:45 上午
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public static final String ERROR_MESSAGE = "访问路径：{},错误信息：{},错误行数：{}";


    /**
     * 处理属性检验异常
     *
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    public R arithmeticExceptionHandler(HttpServletRequest request, ArithmeticException e) {
        log.error(ERROR_MESSAGE, request.getRequestURI(), e.getMessage(), e.getStackTrace()[0]);
        e.printStackTrace();
        return R.fail(RESULT_SERVER_ERR_CODE, e.getMessage());
    }

    /**
     * 处理运行时异常
     *
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public R arithmeticExceptionHandler(HttpServletRequest request, RuntimeException e) {
        log.error(ERROR_MESSAGE, request.getRequestURI(), e.getMessage(), e.getStackTrace()[0]);
        e.printStackTrace();
        return R.fail(RESULT_SERVER_ERR_CODE, e.getMessage());
    }

    /**
     * 空指针异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public R nullPointerException(HttpServletRequest request, NullPointerException e) {
        log.error(ERROR_MESSAGE, request.getRequestURI(), e.getMessage(), e.getStackTrace()[0]);
        e.printStackTrace();
        return R.fail(RESULT_SERVER_ERR_CODE, "操作失败");
    }

    /**
     * 有效验证异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(ValidateException.class)
    public R validateException(HttpServletRequest request, ValidateException e) {
        log.error(ERROR_MESSAGE, request.getRequestURI(), e.getMessage(), e.getStackTrace()[0]);
        e.printStackTrace();
        return R.fail(RESULT_SERVER_ERR_CODE, "会话过期，请重新登录");
    }

    @ExceptionHandler(Exception.class)
    public R exception(HttpServletRequest request, Exception e) {
        log.error(ERROR_MESSAGE, request.getRequestURI(), e.getMessage(), e.getStackTrace()[0]);
        e.printStackTrace();
        return R.fail(RESULT_SERVER_ERR_CODE, e.getMessage());
    }
}
