package com.younike.common.exception;

import com.younike.common.bean.APIResult;
import com.younike.common.bean.ApiResultCode;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
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;

/**
 * @author OldMa
 * @version 1.0.0
 * @ClassName ApiResultCode.java
 * @Description TODO
 * @createTime 2021年06月10日 13:45:00
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public APIResult operateExp(RuntimeException ex, HttpServletRequest request) {

        APIResult result = new APIResult();
        logger.error(ex.getMessage());
        if(!ObjectUtils.isEmpty(ex.getStackTrace())){
            for (StackTraceElement stackTraceElement : ex.getStackTrace()) {
                logger.error(stackTraceElement.toString());
            }
        }
        if(ex instanceof UnauthenticatedException){
            result.setCode(401);
            result.setMsg("登录过期，请重新登录");
            return result;
        }

        if(ex instanceof ApiException){
            result.setCode(((ApiException) ex).getCode());
            result.setMsg(ex.getMessage());
            return result;
        }
        result.setCode(ApiResultCode.Fail.getCode());
        result.setMsg(ex.getMessage());
        return result;
    }

    /**
     * 非runtime异常捕捉，提示开发人员需要修改
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public APIResult otherExp(Exception ex, HttpServletRequest request) {

        /**
         * 参数异常
         */
        if(ex instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            String message = exception.getBindingResult().getFieldError().getDefaultMessage();
            APIResult result = new APIResult();
            result.setCode(ApiResultCode.Fail.getCode());
            result.setMsg(message);
            return result;
        }

        APIResult result = new APIResult();
        result.setCode(ApiResultCode.Fail.getCode());
        result.setMsg(ex.getMessage());
        return result;
    }
}
