package cn.axzo.msg.center.http;

import cn.axzo.basics.common.exception.ServiceException;
import cn.azxo.framework.common.model.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
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 java.util.List;

/**
 * @author yanglin
 */
@Slf4j
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ControllerExceptionAdvice {

    @ExceptionHandler(value = ServiceException.class)
    public CommonResponse<?> bizException(ServiceException e) {
        log.warn("ControllerExceptionHandler.bizException Exception", e);
        return CommonResponse.error(e.getErrorCode(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public CommonResponse<Void> bindExceptionHandler(BindException e) {
        log.warn("业务异常", e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if (CollectionUtils.isEmpty(allErrors)) {
            return CommonResponse.fail("操作失败 请联系系统管理员");
        }
        ObjectError objectError = allErrors.get(0);
        String objectErrorDefaultMessage = objectError.getDefaultMessage();
        return CommonResponse.fail(objectErrorDefaultMessage);
    }
}