package com.zcxk.exception;

import com.zcxk.model.AjaxMessage;
import com.zcxk.model.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GloabalExceptionHandle {






    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public AjaxMessage globalException(HttpServletRequest request, HandlerMethod handlerMethod, Throwable ex) {
            log.error("系统错误",ex);
            return new AjaxMessage<>(ResultStatus.ERROR_500,ex.getMessage());


    }

    /**
     * 判断是否是Ajax请求
     *
     * @param request
     * @return
     */
    public boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null &&
                "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
//    @ExceptionHandler(Exception.class)
//    public Result globalException(HttpServletRequest request, Throwable ex) {
//        return new Result(getStatus(request).value(),"访问出错，无法访问: " + ex.getMessage(),null);
//    }


    /**
     * 获取响应状态码
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

    /**
     * 捕捉404异常,这个方法只在配置
     * spring.mvc.throw-exception-if-no-handler-found=true来后起作用
     *
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public AjaxMessage handle(HttpServletRequest request,NoHandlerFoundException e) {
        System.out.println(12);

        return  new AjaxMessage<>(ResultStatus.ERROR_500);
    }
}
