package com.ruoyi.benyun.error;

import com.ruoyi.benyun.error.entity.BenYunCoreCodeEnum;
import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@Slf4j  //lombok的日志记录
@RestControllerAdvice
public class BenYunCoreControllerAdver {
    /*
     * 精确匹配异常处理
     * */
    @ExceptionHandler(value = BindException.class)
    public R handleVaildException(BindException e){
        //获取BindingResult
        BindingResult result = e.getBindingResult();

        //1.创建Map，用于存储错误信息
        HashMap<String,String> hashMap = new HashMap<>();

        //2.将错误信息放入map
        FieldError fieldError = result.getFieldErrors().get(0);


        //3.返回错误信息
        return R.fail(400,fieldError.getDefaultMessage());
    }

    /*
     * 所有异常处理
     * */
    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){

        //记录错误信息
        log.error(e.getMessage());
        e.printStackTrace();


        return R.fail(BenYunCoreCodeEnum.OTHER_ERROR.getCode(), BenYunCoreCodeEnum.OTHER_ERROR.getMsg());
    }
}
