package org.jeecg.common.exception;

import cn.hutool.core.util.StrUtil;
import org.jeecg.common.api.vo.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: niugeng
 * @create: 2024-01-02 17:22
 **/
@RestControllerAdvice
public class GlobalVaildExceptionHandler {

    /**
     * 处理单个字段验证失败的异常
     * @param e
     * @return {@link Result}<{@link Object}>
     */
    @ExceptionHandler(BindException.class)
    public Result<Object> handleBindException(BindException e) {
        FieldError fieldError = e.getFieldError();
        final String msg = StrUtil.format("({}:{})",fieldError.getField() , fieldError.getDefaultMessage()) ;
        return Result.error(msg);
    }


    /**
     * 处理@Valid触发的方法参数验证失败的异常
     * @param ex
     * @return {@link Result}<{@link Object}>
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        // 获取错误信息列表
        List<String> errors = ex.getBindingResult().getFieldErrors().stream()
                .map(fieldError ->StrUtil.format("({}:{})",fieldError.getField() , fieldError.getDefaultMessage()))
                .collect(Collectors.toList());
        final String collect = errors.stream().collect(Collectors.joining(""));
        return Result.error(collect);
    }


}
