package com.prolog.cs.base.gsp.core;

import com.prolog.framework.common.message.RestMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

@RestControllerAdvice
public class ControllerExceptionAdvice {

    //某个字段为空
    @ExceptionHandler({BindException.class})
    public RestMessage<Object> methodArgumentNotValidExceptionHandler(BindException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return RestMessage.newInstance(false, objectError.getDefaultMessage(), null);
    }

    @ExceptionHandler({ValidationException.class})
    public RestMessage<Object> methodArgumentNotValidExceptionHandler(ValidationException e) {
        return RestMessage.newInstance(false, e.getMessage(), null);
    }

    //列表参数没有传
    @ExceptionHandler({ConstraintViolationException.class})
    public RestMessage<Object> methodArgumentNotValidExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> set = e.getConstraintViolations();
        String result = set.stream().map(ConstraintViolation::getMessage).distinct().findFirst().orElse(null);
        return RestMessage.newInstance(false, result == null ? "请求参数不能为空" : result, null);
    }

    //请求参数没用传
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public RestMessage<Object> methodArgumentNotValidExceptionHandler() {
        return RestMessage.newInstance(false, "请求参数不能为空", null);
    }
}
