package cn.axzo.workflow.server.advice;

import cn.axzo.framework.autoconfigure.web.exception.RespErrorCodeMappingProperties;
import cn.axzo.framework.autoconfigure.web.exception.handler.AbstractExceptionApiResultHandler;
import cn.axzo.framework.domain.web.code.IRespCode;
import cn.axzo.framework.domain.web.code.RespCode;
import cn.axzo.workflow.core.common.exception.WorkflowEngineException;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.FlowableException;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static cn.axzo.framework.domain.web.code.BaseCode.UNAVAILABLE_FOR_LEGAL_REASONS;

/**
 * 针对 Flowable 引擎内部异常直接抛出给调用方的异常处理器
 *
 * @author wangli
 * @since 2023/12/8 12:52
 */
@Component
@Slf4j
public class FlowableExceptionResultHandlerAdvice extends AbstractExceptionApiResultHandler<FlowableException> {
    public FlowableExceptionResultHandlerAdvice(RespErrorCodeMappingProperties properties) {
        super(properties);
    }

    @Override
    protected IRespCode decode(FlowableException ex, IRespCode fallbackCode) {
        log.warn("发现 FlowableException Error: ", ex);
        if (Objects.nonNull(ex.getCause()) && ex.getCause() instanceof WorkflowEngineException) {
            return new RespCode(UNAVAILABLE_FOR_LEGAL_REASONS.getCode(), ex.getCause().getMessage());
        }
        return new RespCode(UNAVAILABLE_FOR_LEGAL_REASONS.getCode(), ex.getMessage());
    }
}
