package com.dxhy.domestic.config;

import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dxhy.common.utils.R;

import lombok.extern.slf4j.Slf4j;

/**
 * @author dxhy
 */
@Slf4j
@ControllerAdvice
public class DxExceptionHandler {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>>
        methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException exception) {

        StringBuilder sb = new StringBuilder("参数校验异常，");
        exception.getBindingResult().getAllErrors().forEach(error -> {
            if (error instanceof FieldError) {
                sb.append(((FieldError)error).getField()).append(error.getDefaultMessage());
            }
        });
        log.error("参数校验异常", exception);

        return ResponseEntity.ok(R.error(sb.toString()));
    }

}
