package org.springblade.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 *
 * 处理 @Validated 异常信息
 *
 */
@Slf4j
@RestControllerAdvice("org.springblade.modules")
public class GlobalValidExceptionHandler {

    /**
     * 参数效验异常处理器
     *
     * @param  e 参数验证异常
     * @return R
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R parameterExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
        log.warn("Url:{}, Method:{}, Controller called error!Catch in ErrorHandler", req.getRequestURI(), req.getMethod(), e);
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return R.fail(fieldError.getDefaultMessage());
            }
        }
        return R.fail("GlobalValidExceptionHandler异常处理信息.");
    }
}
