package com.testor.handler;


import com.testor.common.core.domain.BaseResponse;
import com.testor.common.security.handler.GlobalExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.*;

/**
 * 全局异常处理器
 *
 * @author 
 */
@RestControllerAdvice
public class GloballyExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public BaseResponse<List<String>> ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        log.error("----------------------捕获到异常------------------------");
        BaseResponse<List<String>> baseResponse = new BaseResponse();
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        baseResponse.setMsg(msgList.toString());
        return baseResponse;
    }

}
