package com.artfess.device.exception;

import com.artfess.base.enums.ResponseErrorEnums;
import com.artfess.base.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 表单字段验证
 *
 * @author min.wu
 * @date 2022-07-12
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.artfess.device")
public class VaildExceptionControllerAdvice {

    /**
     * 统一处理异常，可以使用Exception.class先打印一下异常类型来确定具体异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}, 异常类型:{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        // 获取校验的错误结果
        result.getFieldErrors().forEach((item) -> {
            // 获取错误的属性名字 + 获取到错误提示FieldError
            errorMap.put(item.getField(), item.getDefaultMessage());
        });
        return new CommonResult<>(ResponseErrorEnums.REQUIRED_ERROR, errorMap);
    }

}
