package cn.axzo.workflow.server.controller.web.exception;

import cn.axzo.basics.common.exception.ServiceException;
import cn.azxo.framework.common.model.CommonResponse;
import lombok.extern.slf4j.Slf4j;
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;

/**
 * Controller异常
 * @author zuoqinbo
 * @version V1.0
 * @date 2023/11/11 9:44
 */

@Order(value = 0)
@RestControllerAdvice
@Slf4j
public class ExceptionAdviceHandler {

    @ExceptionHandler(ServiceException.class)
    public CommonResponse<Void> basicsServiceExceptionHandler(ServiceException e) {
        log.warn("业务异常", e);
        return CommonResponse.fail(e.getMessage());
    }

    @ExceptionHandler(cn.axzo.core.service.ServiceException.class)
    public CommonResponse<Void> coreServiceExceptionHandler(cn.axzo.core.service.ServiceException e) {
        log.warn("业务异常", e);
        return CommonResponse.fail(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);
    }

}
