package com.sysu.admin.support.validated;

import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

/**
 * 统一校验异常处理类
 */
@RestControllerAdvice
public class BindExceptionHanlder {


    @ExceptionHandler(BindException.class)
    public BaseResult handleBindException(HttpServletRequest request, BindException exception) {
        List<FieldError> allErrors = exception.getFieldErrors();
        StringBuilder sb = new StringBuilder(100);
        for (FieldError errorMessage : allErrors) {
            sb.append(errorMessage.getDefaultMessage());
            break;
        }
        return R.fail(sb.toString());
    }
}