package com.artfess.base.exception;

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.ljzc")
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<>();
        StringBuffer sb = new StringBuffer();
        // 获取校验的错误结果
        result.getFieldErrors().forEach((item) -> {
            // 获取错误的属性名字 + 获取到错误提示FieldError
            String message = item.getDefaultMessage();
            sb.append(",");
            sb.append(message);
            errorMap.put(item.getField(), message);
        });
        String message = null;
        if (sb.length() > 0) {
            message = sb.substring(1);
        }
        return new CommonResult(false,  message, null);
    }

}
