springboot 全局异常统一处理及流程引擎

流程引擎

  • 定义流程引擎,解耦业务,统一入口
  • 引擎应与协议层解耦
  • 所以异常直接抛出,统一处理
package xx.biz;

import xx.biz.action.BaseAction;
import xx.model.AbstractRequest;
import xx.model.CommonResponse;
import xx.model.Content.BizCodeEnum;
import xx.util.enumutil.ProcessEnum;
import xx.util.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author 
 * @date 2021/2/3 20:07
 * @description 处理流程入口
 */
@Component
public class ProcessFlow implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(ProcessFlow.class);

    private ApplicationContext applicationContext;

    /**
     * 流程控制
     *
     * @param request     请求参数
     * @param processEnum 流程枚举
     */
    public Object process(AbstractRequest request, ProcessEnum processEnum,
                          Map<String, Object> expand) throws Exception {
        logger.info("ProcessFlow.process...start request={},process code={}", request, processEnum.getCode());
        Object result = null;
        List<String> processTemplate = processEnum.getProcessTemplate();
        if (CollectionUtils.isEmpty(processTemplate)) {
            throw new BizException(BizCodeEnum.PROCESS_TEMPLATE_EMPTY_EXCEPTION);
        }
        for (String template : processTemplate) {
            BaseAction action;
            try {
                action = applicationContext.getBean(template, BaseAction.class);
            } catch (Exception e) {
                throw new BizException(BizCodeEnum.PROCESS_TEMPLATE_NOT_FOUND_EXCEPTION);
            }
            Object execute = action.execute(request, expand);
            if (execute != null) {
                result = execute;
            }
        }
        logger.info("ProcessFlow.process...end result={}", request);
        return result;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

全局异常统一处理

为了更专注于业务,减少不必要的工作,在项目中应有全局异常统一处理

package xx.config.web;

import xx.model.CommonResponse;
import xx.model.Content.BizCodeEnum;
import xx.model.Content.CommonContent;
import xx.util.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 
 * @version 1.0
 * @description 异常全局处理
 * @date 2021/2/27 8:25
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常处理
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public CommonResponse bizExceptionHandler(HttpServletRequest req, BizException e) {
        CommonResponse response = new CommonResponse();
        response.setCode(e.getErrorCode());
        response.setMemo(e.getErrorMessage());
        return response;
    }

    /**
     * 参数绑定异常处理
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResponse methodArgumentNotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
        CommonResponse response = new CommonResponse();
        response.setCode(BizCodeEnum.PARAMS_ILLEGAL.getCode());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> errorInfo=new ArrayList<>();
        allErrors.forEach(eInfo->{
            errorInfo.add(eInfo.getDefaultMessage());
        });
        response.setMemo(BizCodeEnum.PARAMS_ILLEGAL.getMemo()+ CommonContent.COLON +errorInfo.toString());
        return response;
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public CommonResponse nullPointerExceptionHandler(HttpServletRequest req, NullPointerException e) {
        CommonResponse response = new CommonResponse();
        response.setCode(BizCodeEnum.SYS_ERROR.getCode());
        response.setMemo(BizCodeEnum.SYS_ERROR.getMemo());
        return response;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResponse otherExceptionHandler(HttpServletRequest req,Exception e) {
        logger.error("GlobalExceptionHandler.otherExceptionHandler...e=",e);
        CommonResponse response = new CommonResponse();
        response.setCode(BizCodeEnum.SYS_ERROR.getCode());
        response.setMemo(BizCodeEnum.SYS_ERROR.getMemo());
        return response;
    }



}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值