SpringBoot 项目异常设计

37 篇文章 0 订阅
8 篇文章 0 订阅

1、一个全局异常类:

package com.amc.act.exception;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amc.act.constant.ResultConstant;
import com.amc.act.dto.response.BaseResponse;
import com.amc.act.dto.response.LouBaseResponse;
import com.amc.act.entity.TsactLogErrorEntity;
import com.amc.act.mapper.TsactLogErrorMapper;
import com.amc.act.util.GenerateSequenceUtil;


@ControllerAdvice
public class GlobalExceptionHandle {

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

    @Autowired
    private TsactLogErrorMapper errorMapper;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<?> handle(Exception e) {
        List<String> msgList = new ArrayList<String>();
        if (e instanceof actException) {
            actException exception = (actException) e;
            logger.error("【业务异常】======>" + exception.toString());
            return new ResponseEntity<BaseResponse>(new BaseResponse(exception.getErrorMsg(), exception.getErrorCode(),
                    ResultConstant.FAILURE_RESULT_CODE), HttpStatus.OK);
        } else if (e instanceof BusinessRecordException) {
            // 异常插入error表
            BusinessRecordException exception = (BusinessRecordException) e;
            logger.error("【业务异常】======>" + exception.toString());
            TsactLogErrorEntity entity = new TsactLogErrorEntity();
            List<String> errorMsg = exception.getErrorMsg();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < errorMsg.size(); i++) {
                if (i != 0) {
                    sb.append("; ");
                }
                sb.append(errorMsg.get(i));
            }
            entity.setRegionCode(exception.getRegionCode());
            entity.setFailReason(sb.toString());
            entity.setDistributorNumber(exception.getDistributorNumber());
            entity.setTransactionCode(GenerateSequenceUtil.generateSequenceNo());
            errorMapper.insert(entity);
            return new ResponseEntity<BaseResponse>(new BaseResponse(exception.getErrorMsg(), exception.getErrorCode(),
                    ResultConstant.FAILURE_RESULT_CODE), HttpStatus.OK);
        } else if (e instanceof LouException) {
            LouException exception = (LoukException) e;
            logger.error("【业务异常】======>" + exception.toString());
            return new ResponseEntity<LouBaseResponse>(new LouBaseResponse(exception.getErrorParams(),
                    exception.getErrorCode(), exception.getLouactations()), HttpStatus.OK);
        } else {
            logger.error("【系统异常】======>", e);
            msgList.add("系统异常");
            return new ResponseEntity<BaseResponse>(new BaseResponse(msgList, ResultConstant.ERR_SYSTEM_EXCEPTION,
                    ResultConstant.FAILURE_RESULT_CODE), HttpStatus.OK);
        }
    }

}

 

项目基础返回类:

package com.amc.act.dto.response;

import java.util.ArrayList;
import java.util.List;


public class BaseResponse {

    private String resultCode = "0";

    private List<String> errorParams = new ArrayList<String>();

    private String errorCode = "";

    public BaseResponse() {
        super();
    }

    public BaseResponse(List<String> errorParams) {
        super();
        this.errorParams = errorParams;
    }

    public BaseResponse(List<String> errorParams, String resultCode) {
        super();
        this.errorParams = errorParams;
        this.resultCode = resultCode;
    }

    public BaseResponse(List<String> errorParams, String errorCode, String resultCode) {
        super();
        this.resultCode = resultCode;
        this.errorParams = errorParams;
        this.errorCode = errorCode;
    }
.............省略get,set方法

package com.amc.act.dto.response;

import java.util.ArrayList;
import java.util.List;

public class LouBaseResponse {
    private String resultCode = "0";

    private List<String> errorParams = new ArrayList<String>();

    private String errorCode = "";

    private List<LouRsponse> louacts;

public LouBaseResponse(List<String> errorParams, String errorCode, List<LouRsponse> LouAct) {
        super();
        this.errorParams = errorParams;
        this.errorCode = errorCode;
        this.LouAct = LouAct;
    }

    public LouBaseResponse(String resultCode, List<String> errorParams, String errorCode,
            List<LouRsponse> LouAct) {
        super();
        this.resultCode = resultCode;
        this.errorParams = errorParams;
        this.errorCode = errorCode;
        this.LouAct = LouAct;

..........省略get,set方法

 


2、自定义异常类

a.直接抛异常的自定义异常

package com.amc.act.exception;

import java.util.ArrayList;
import java.util.List;

public class ActException extends RuntimeException {

    private static final long serialVersionUID = 4943411810276869978L;

    private String errorCode = "";

    private List<String> errorMsg = new ArrayList<String>();

    public ActException(List<String> errorMsg) {
        super();
        this.errorMsg = errorMsg;
    }

    public ActException(String errorCode, List<String> errorMsg) {
        super();
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

............省略get,set方法

b.需要將业务异常记录信息到表里的自定义异常

package com.amc.act.exception;

import java.util.ArrayList;
import java.util.List;

public class BusinessRecordException extends RuntimeException {

    private static final long serialVersionUID = 1795679592675750616L;

    private String errorCode = "";

    private List<String> errorMsg = new ArrayList<String>();

    private String subNo;

    private String subCode;

    public BusinessRecordException(String errorCode, List<String> errorMsg, String subNo, String subCode) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.subNo = subNo;
        this.subCode = subCode;
    }

.........省略get,set方法

c.需要将异常的详细信息返回页面

package com.amc.act.exception;

import java.util.ArrayList;
import java.util.List;

import com.amc.act.dto.response.LouRsponse;

public class LouException extends RuntimeException {

    private String resultCode = "0";

    private List<String> errorParams = new ArrayList<String>();

    private String errorCode = "";

    private List<LouRsponse> louActs;

    public LouException(List<String> errorParams, String errorCode, List<LouRsponse> louActs) {
        super();
        this.errorParams = errorParams;
        this.errorCode = errorCode;
        this.louActs = louActs;
    }

..........省略get,set方法

详细内容信息: 可多层嵌套

package com.amc.act.dto.response;

import java.util.List;

public class LouRsponse {


    private String act;

    private Integer count;

    private List<Contents> contents;

.........省略get,set方法

3、全局异常类注解介绍

a、@ControllerAdvice
源码

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//bean对象交给spring管理生成
@Component
public @interface ControllerAdvice {
    @AliasFor("basePackages")
    String[] value() default {};

    @AliasFor("value")
    String[] basePackages() default {};

    Class<?>[] basePackageClasses() default {};

    Class<?>[] assignableTypes() default {};

    Class<? extends Annotation>[] annotations() default {};
}

b、@ExceptionHandler
源码

//该注解作用对象为方法
@Target({ElementType.METHOD})
//在运行时有效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
    //value()可以指定异常类
    Class<? extends Throwable>[] value() default {};
}

所以结合上面我们可以知道,使用@ExceptionHandler,可以处理异常, 但是仅限于当前Controller中处理异常, @ControllerAdvice可以配置basePackage下的所有controller. 所以结合两者使用,就可以处理全局的异常了.

基于@ControllerAdvice注解的全局异常统一处理只能针对于Controller层的异常,意思是只能捕获到Controller层的异常。

如果Controller层对异常进行了catch处理,那么在这里就不会捕获到Controller层的异常了,所以这一点要特别注意。

如果在Controller中不做异常catch处理,在service中抛出异常(service中也不做异常catch处理),那么也是可以在这里捕获到异常的。
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值