博客
关于我
springboot统一异常处理
阅读量:584 次
发布时间:2019-03-11

本文共 3752 字,大约阅读时间需要 12 分钟。

Spring Boot 统一异常处理实践指南

在软件开发过程中,异常处理是保障系统稳定运行的重要环节。通过统一异常处理,我们可以将系统中出现的各种异常进行集中管理和处理,从而实现对异常状态的快速响应和定位。

制造异常情景

为了更好地理解异常处理的重要性,我们可以先通过制造特定的异常情景来观察系统的反应。例如,在业务逻辑中引入一个标记字段 @TableField(value = "is_deleted")private Boolean deleted;,并在需要的位置抛出异常。这个标记字段通常用于表示记录是否被逻辑删除。

创建异常处理工具类

guli-framework-common 模块的 com.guli.common.util 包中,我们创建了一个异常处理工具类 ExceptionUtil.java

public class ExceptionUtil {    public static String getMessage(Exception e) {        StringWriter sw = null;        PrintWriter pw = null;        try {            sw = new StringWriter();            pw = new PrintWriter(sw);            e.printStackTrace(pw);            pw.flush();            sw.flush();        } finally {            if (sw != null) {                try {                    sw.close();                } catch (IOException e1) {                    e1.printStackTrace();                }            }            if (pw != null) {                pw.close();            }        }        return sw.toString();    }}

这个工具类能够将异常信息转换为易于阅读和处理的字符串形式,便于日志记录和前端显示。

全局异常处理器

guli-framework-common 模块的 com.guli.common.handler 包中,我们创建了一个全局异常处理类 GlobalExceptionHandler.java

package com.guli.common.handler;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;import java.util.Map;@ControllerAdvice@Slf4jpublic class GlobalExceptionHandler {    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);    @ExceptionHandler(Exception.class)    @ResponseBody    public R error(Exception e) {        log.error(ExceptionUtil.getMessage(e));        return R.error();    }    @ExceptionHandler(BadSqlGrammarException.class)    @ResponseBody    public R error(BadSqlGrammarException e) {        log.error(ExceptionUtil.getMessage(e));        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);    }    @ExceptionHandler(HttpMessageNotReadableException.class)    @ResponseBody    public R error(HttpMessageNotReadableException e) {        log.error(ExceptionUtil.getMessage(e));        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);    }    @ExceptionHandler(GuliException.class)    @ResponseBody    public R error(GuliException e) {        log.error(ExceptionUtil.getMessage(e));        return R.error().message(e.getMessage()).code(e.getCode());    }}

这个类通过 @ControllerAdvice 注解,能够统一拦截所有定义的异常类型,并通过 @ResponseBody 返回适当的响应对象。

自定义异常类

为了满足业务需求的特殊性,我们在 com.guli.common.exception 包中创建了一个通用的自定义异常类 GuliException.java

package com.guli.common.exception;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiProperty;import org.springframework.lang.annotation.ApiResponseObject;@ApiModel(value = "全局异常")public class GuliException extends RuntimeException {    @ApiProperty(value = "状态码")    private Integer code;    @ApiProperty(value = "错误信息")    private String message;    public GuliException(Integer code, String message) {        super(message);        this.code = code;    }    public GuliException(ResultCodeEnum resultCodeEnum) {        super(resultCodeEnum.getMessage());        this.code = resultCodeEnum.getCode();    }    @Override    public String toString() {        return "GuliException{" +               "code=" + code +               ",message=" + this.getMessage() +               '}';    }}

这个自定义异常类继承自 RuntimeException,具有无侵入性,同时支持状态码和错误信息的携带,便于统一处理和前端展示。

业务中的异常抛出

在业务逻辑中,我们需要在需要拦截异常的地方声明处理方法。例如:

@ExceptionHandler(GuliException.class)@ResponseBodypublic R error(GuliException e) {    log.error(ExceptionUtil.getMessage(e));    return R.error().message(e.getMessage()).code(e.getCode());}

通过这种方式,我们可以集中管理系统中出现的各种异常,实现对异常状态的快速响应和定位。

转载地址:http://gjgvz.baihongyu.com/

你可能感兴趣的文章
NIFI大数据进阶_外部ZK模式集群1_实际操作搭建NIFI外部ZK模式集群---大数据之Nifi工作笔记0017
查看>>
NIFI大数据进阶_实时同步MySql的数据到Hive中去_可增量同步_实时监控MySql数据库变化_操作方法说明_01---大数据之Nifi工作笔记0033
查看>>
NIFI大数据进阶_离线同步MySql数据到HDFS_01_实际操作---大数据之Nifi工作笔记0029
查看>>
NIFI大数据进阶_离线同步MySql数据到HDFS_02_实际操作_splitjson处理器_puthdfs处理器_querydatabasetable处理器---大数据之Nifi工作笔记0030
查看>>
NIFI大数据进阶_离线同步MySql数据到HDFS_说明操作步骤---大数据之Nifi工作笔记0028
查看>>
NIFI大数据进阶_连接与关系_设置数据流负载均衡_设置背压_设置展现弯曲_介绍以及实际操作---大数据之Nifi工作笔记0027
查看>>
NIFI数据库同步_多表_特定表同时同步_实际操作_MySqlToMysql_可推广到其他数据库_Postgresql_Hbase_SqlServer等----大数据之Nifi工作笔记0053
查看>>
NIFI汉化_替换logo_二次开发_Idea编译NIFI最新源码_详细过程记录_全解析_Maven编译NIFI避坑指南001---大数据之Nifi工作笔记0068
查看>>
NIFI汉化_替换logo_二次开发_Idea编译NIFI最新源码_详细过程记录_全解析_Maven编译NIFI避坑指南002---大数据之Nifi工作笔记0069
查看>>
NIFI集群_内存溢出_CPU占用100%修复_GC overhead limit exceeded_NIFI: out of memory error ---大数据之Nifi工作笔记0017
查看>>
NIFI集群_队列Queue中数据无法清空_清除队列数据报错_无法删除queue_解决_集群中机器交替重启删除---大数据之Nifi工作笔记0061
查看>>
NIH发布包含10600张CT图像数据库 为AI算法测试铺路
查看>>
Nim教程【十二】
查看>>
Nim游戏
查看>>
NIO ByteBuffer实现原理
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
nio 中channel和buffer的基本使用
查看>>
NIO_通道之间传输数据
查看>>
NIO三大组件基础知识
查看>>