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

本文介绍如何在SpringBoot项目中统一处理异常,通过自定义枚举类、异常类、返回报文实体类等步骤,实现对学生年龄的有效验证并给出提示。

       本随笔记录使用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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 ,查看结果。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值