package com.YuyeTech.TPlat.handler;

import com.YuyeTech.TPlat.VO.ResultVO;
import com.YuyeTech.TPlat.enums.UserEnum;
import com.YuyeTech.TPlat.exception.AuthorizeException;
import com.YuyeTech.TPlat.exception.UserException;
import com.YuyeTech.TPlat.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 捕获异常
 * @author:slambb
 * @date:2019/12/13
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    //拦截登录异常
    @ExceptionHandler(value = AuthorizeException.class)
    @ResponseBody
    public ResultVO handlerAuthorizeException(AuthorizeException e){
        log.info("捕获信息异常{}，{}",e.getCode(),e.getMessage());
        return ResultVOUtil.error(e.getCode(),e.getMessage());
    }

    //用户信息异常
    @ExceptionHandler(value = UserException.class)
    @ResponseBody
    public ResultVO handlerUserException(UserException e){

        return ResultVOUtil.error(e.getCode(),e.getMessage());
    }

    //表单错误
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ResultVO handlerBindException(BindException e){
//        log.info(e.getMessage());
//        log.info(e.getAllErrors().toString());
        List<ObjectError> errors=e.getAllErrors();
        String msg=errors.get(0).getDefaultMessage();//获取自错误信息
        return ResultVOUtil.error(200 ,msg);
    }


    //捕获设置了形参,但是在访问该方法时,没有传参的异常
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public ResultVO handlerServletRequestParameterException(MissingServletRequestParameterException e){
        return ResultVOUtil.error(UserEnum.USER_PARAMETER_NOT_PRESENT.getCode(),e.getMessage());

//        ResultVO resultVO = new ResultVO();
//        resultVO.setCode(500);
//        resultVO.setMsg(e.getMessage());
//        resultVO.setData(e);
//        return resultVO;
    }
//    {
//        "timestamp": "2019-12-21T14:37:23.363+0000",
//            "status": 400,
//            "error": "Bad Request",
//            "message": "Required String parameter 'userId' is not present",
//            "path": "/smallshop/user_info/get_user_info"
//    }
}
