package com.shanghaichengdi.ghjgitem.config;

import com.alibaba.fastjson.JSON;
import com.shanghaigeography.entity.ResultMsg;
import com.shanghaigeography.eum.ResultState;
import java.util.ArrayList;
import java.util.List;
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.RestControllerAdvice;

@RestControllerAdvice
public class BadRequestExceptionHandler {

  /**
   * 校验错误拦截处理
   *
   * @param exception 错误信息集合
   * @return 错误信息
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  public String validationBodyException(MethodArgumentNotValidException exception) {
    BindingResult result = exception.getBindingResult();
    List<String> ms = new ArrayList<>();
    if (result.hasErrors()) {
      List<ObjectError> errors = result.getAllErrors();
      errors.forEach(p -> {
        FieldError fieldError = (FieldError) p;
        ms.add(fieldError.getDefaultMessage());
      });
    }
    return new ResultMsg<String>().setCode(ResultState.ERROR_NEEDDATA)
        .setMsg("parameters error,Verify the following parameters").setData(JSON.toJSONString(ms))
        .toJSON();
  }
}
