Spring Boot学习——统一异常处理

本随笔记录使用Spring Boot统一处理异常。

本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间。小于14岁,提示“你可能在上初中”;大于20岁,提示“呢可能在上大学”。

第一步,创建枚举类ResultEnum,用来管理异常信息

package *;//自己定义

public enum ResultEnum {
    UNKONW_ERROR(-1, "未知错误"),
    SUCCESS(0, "成功"),
    PRIMARY_SCHOOL(100, "年龄小于14岁,可能正在上中学"),
    UNIVERSITY(101, "年龄大于20岁,可能正在上大学");

    private Integer code;
    private String msg;

    ResultEnum( Integer code, String msg){
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode(){
        return  this.code;
    }

    public String getMsg(){
        return this.msg;
    }
}

第二步,创建自己的异常类StudentException,代码如下:

package *;//自己定义

import *.ResultEnum; //自己定义路径

public class StudentException extends RuntimeException {
    private Integer code;

    public StudentException(ResultEnum resultEnum){
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }
}

第三步,创建返回报文实体类Result.java

package *;//自己定义

import *.Result; //自己定义的路径

/**
 * HTTP请求返回处理工具类
 */
public class ResultUtil {
    public static Result success(){
        return success(null);
    }
    public static Result success(Object object){
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setDate(object);
        return result;
    }

    public static Result error(Integer code, String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

  第四步,创建请求返回工具类ResultUtil.java

package *;//自己定义

import *.Result;//自己定义的路径

/**
 * HTTP请求返回处理工具类
 */
public class ResultUtil {
    public static Result success(){
        return success(null);
    }
    public static Result success(Object object){
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setDate(object);
        return result;
    }

    public static Result error(Integer code, String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

第五步,创建统一处理异常的类ExceptionHandle.java,代码如下:

package *; //自己定义

import *.StudentException; //自己定义路径
import *.Result; //自己定义路径
import *.ResultUtil; //自己定义路径
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handler( Exception e){
        if( e instanceof StudentException){
            StudentException studentException = (StudentException) e;
            return ResultUtil.error( studentException.getCode(), studentException.getMessage());
        }else {
            logger.info("[系统异常] {}",e);
            return ResultUtil.error( -1, "未知错误");
        }
    }
}

第六步,在service中编写业务逻辑代码:

package *; //自己定义

import *.ResultEnum; //自己定义的路径
import *.StudentException; //自己定义的路径
import *.StudentRepository; //自己定义的路径
import *.Student; //自己定义的路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    /**
     * 根据ID查询符合条件的学生
     * @param id
     * @throws Exception
     */
    public Student getStudentById( Integer id) throws Exception{
        Student student = studentRepository.findOne(id);
        Integer age = student.getAge();
        if(age < 14){
            throw new StudentException(ResultEnum.PRIMARY_SCHOOL);
        }else if(age > 20){
            throw new StudentException(ResultEnum.UNIVERSITY);
        }

        //进行下面逻辑操作
        return student;
    }
}

第七步,在controller中调用service方法,代码如下:

package *; //自己定义路径

import *.Result; //自己定义路径
import *.StudentService; //自己定义路径
import *.ResultUtil; //自己定义路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * 根据ID查询学生
     */
    @GetMapping(value = "/student/getage/{id}")
    public Result getStudentById(@PathVariable("id") Integer id) throws Exception{
        return ResultUtil.success(studentService.getStudentById(id));
    }

}

最后,使用postman访问http://127.0.0.1:8080/student/getage/1 ,查看结果。

时间: 2024-08-27 15:40:26

Spring Boot学习——统一异常处理的相关文章

基于Spring Boot的统一异常处理设计

摘自:https://www.cnblogs.com/greyzeng/p/11733327.html Practitioner 需要不断努力,才能毫不费力 基于Spring Boot的统一异常处理设计 基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支持RestControllerAdvice统一处理异常,在一个请求响应周期当中,如果Contro

基于spring boot的统一异常处理

一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我们认为制造一个异常 @GetMapping(value = "/girls") public List<Girl> girlList() throws Exception{ throw new Exception("错误"); } 使用浏览器访问http:/

spring boot 2 统一异常处理

spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestControllerAdvice public class GatewayExceptionHandler { /*@ExceptionHandler(Exception.class) public JsonResult handleBusinessException(HttpServletRequest r

Spring Boot学习路线

Spring Boot 学习路线,本文计划根据作者近几年的工作.学习经验,来分析和制定一个学习使用 Spring Boot技术的步骤路线图. 一.准备工作 俗话说:"工欲善其事必先利其器".特别是软件开发,这样一个重视工程实践的领域,一定要最先选择和熟悉一系列的开发环境工具. 首先推荐选用最新版本技术标准的开发工具,将如下的开发环境安装配置好. 开发环境: (1)JDK 1.8 (2)Eclipse Oxygen EE版本 或者也可以使用 IntelliJ IDEA (3)Tomcat

15 个优秀开源的 Spring Boot 学习项目

Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受欢迎程度可见一斑.经常有人问松哥有没有推荐的 Spring Boot 学习资料?当然有!买松哥书就对了,哈哈. 有需要书籍<Spring Boot+Vue全栈开发实战>PDF版的同学,可以在公众号:Java知己,发送:全栈开发实战,获取该书籍. 除了书呢?当然就是开源项目了,今天松哥整理了几个优质

Spring Boot学习记录(一)--环境搭建

Spring Boot学习记录(一)–环境搭建 标签(空格分隔): spring-boot 最近趁着下班闲时间学习spring-boot,记录下学习历程,最后打算实战一个API管理平台,下面开始环境配置. 1.工程结构 使用maven建立一个普通结构,因为spring-boot内嵌tomcat,所以打包只需要打包成jar就可以直接运行,所以并不像以前那样建立WEB程序了,目录如下,类可以先建立好放在那: 2.引入maven依赖 根据官方教程提示,直接引入parent就可以使用spring-boo

Spring Boot学习记录(三)--整合Mybatis

Spring Boot学习记录(三)–整合Mybatis 标签(空格分隔): spring-boot 控制器,视图解析器前面两篇都已弄好,这一篇学习持久层框架整合. 1.数据源配置 数据源使用druid,maven引入相关依赖,包括spring-jdbc依赖,mysql依赖 1.转换问题 配置的过程要学会为什么这样配置,而不是只学会了配置.这里我们可以和以前的配置方式对比: 以前版本 <!--配置数据库连接池Druid--> <bean id="dataSource"

Spring Boot学习记录(二)--thymeleaf模板

Spring Boot学习记录(二)–thymeleaf模板 标签(空格分隔): spring-boot 自从来公司后都没用过jsp当界面渲染了,因为前后端分离不是很好,反而模板引擎用的比较多,thymeleaf最大的优势后缀为html,就是只需要浏览器就可以展现页面了,还有就是thymeleaf可以很好的和spring集成.下面开始学习. 1.引入依赖 maven中直接引入 <dependency> <groupId>org.springframework.boot</gr

Spring boot 学习笔记 (二)- 整合MyBatis

Spring boot 学习笔记 (二)- 整合MyBatis Spring Boot中整合MyBatis,并通过注解方式实现映射. 整合MyBatis 以Spring boot 学习笔记 (一)- Hello world 为基础项目,在pom.xml中添加如下依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter&l