1. 程式人生 > >基於SpringBoot+Mybatis開發的簡單異常處理器(ExceptionHandle)

基於SpringBoot+Mybatis開發的簡單異常處理器(ExceptionHandle)

需求:

按照一個人的ID確認他的年齡,如果小於18歲則太年輕,大於65歲則年紀太大。

構思:

一個Person類,按照id查詢Person的age屬性,並對查找出來的age進行判斷。
1.如果年紀小於18,則出現異常“你太年輕”;
2.如果年紀大於65,則出現異常“你年紀太大”。
3.查詢結果要求返回一個Result的Json物件,要求Result中包含:

- 錯誤程式碼(-1為其他錯誤,0為age<18,1為查詢成功,2為age>65)
- 提示資訊(“”後臺錯誤”,“你太年輕”,“查詢成功”,“你年紀太大”)
- 物件資料(查詢成功則輸出查找出的物件,否則輸出為null)

開發流程:

物件

涉及到兩個物件,“Result”和“Person”,其中Person物件與資料庫中person表對應,而Result類則用於輸出JSON資訊到前臺。

####Person類

public class Person {

    private Integer id;//id
    private String personName;//姓名
    private Integer age;//年齡

    public Integer getId() {
        return id;
    }

    public void
setId(Integer id) { this.id = id; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public Integer getAge() { return age; } public void setAge(Integer age)
{ this.age = age; } }

Result類

public class Result {

    //錯誤程式碼
    private Integer code;
    //提示資訊
    private String message;
    //物件資料
    private Object object;

    public Result() {
    }

    public Result(Integer code, String message, Object object) {
        this.code = code;
        this.message = message;
        this.object = object;
    }
    
}

同時,在資料庫中建表:

所建例表

實現:

我們首先可以看到專案包的基本結構:

目錄結構

1.配置application.yml檔案:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
    username: root
    password: admin
server:
  port: 8080
mybatis:
      #mapper檔案路徑
      mapper-locations: classpath:mapper/*.xml
<!D

2.配置personMapper.xml

由於本次需求較為簡單,我們只需要開發一個方法findOne即可:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.simple.dao.PersonMapper">
    <!--根據id查詢person-->
    <select id="findOne" resultType="com.example.simple.POJO.Person">
        SELECT id, person_name AS personName, age FROM person
        WHERE id = #{id}
    </select>
</mapper>

3. DAO層:

注意:區別於SSM,我們不需要再在DAO層加@Repository註解,應為我們在主類SimpleApplication中已經配置了Mapper的自動掃描如圖:

配置圖

package com.example.simple.dao;

import com.example.simple.POJO.Person;

public interface PersonMapper {

    //根據id查詢一個person
    public Person findOne(Integer id);

}

4. service

在這一層我們要對年齡是否符合我們的要求做判斷,所以會令其丟擲異常並對其進行相應的處理。我們前面已經要求對於不合格的年紀要記錄錯誤程式碼,還有提示資訊以及相關資料,所以我們接著來自定義PersonException:

//自定義異常類
public class PersonException extends RuntimeException {

    //錯誤程式碼
    private Integer code;

    public PersonException(Integer code,String message) {
        //用來輸出錯誤資訊
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

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

那麼PersonServiceImpl中的程式碼就有:

@Service
public class PersonServiceImpl implements PersonService {

    //在IDEA環境下,定義的personMapper會報錯,
    //但其實並沒有錯,因為我們已經設定了@MapperScan註解
    @Autowired
    private PersonMapper personMapper;

    @Override
    public Result findAgeById(Integer id) {
        Person person = personMapper.findOne(id);
        //判斷年齡
        if (person.getAge() < 18){
            throw new PersonException(0,"你太年輕了");
        }else if (person.getAge() > 65){
            throw new PersonException(2,"你的年紀太大了");
        }
        return new Result(1,"查詢成功!",person);
    }
}

我們前面已經說過,還要把這個錯誤程式碼和錯誤資訊賦給Result類,再通過它輸出到介面上,所以我們就需要有一個:
####5.ExceptionHandle(異常處理器)處理丟擲的異常資訊:

@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof PersonException) {
            PersonException personException = (PersonException) e;
            return new Result(personException.getCode(), personException.getMessage(), null);
        }else {
            e.printStackTrace();
            return new Result(-1,"後臺錯誤",null);
        }
    }
}

6. 最後是contrller層

@RestController
public class PersonController {

    @Autowired
    private PersonService personService;

    @GetMapping(value = "/getAge/{id}")
    public Result getAgeById(@PathVariable("id") Integer id) {
        return personService.findAgeById(id);
    }
}

7.Postman測試

首先再次擺出資料庫中資訊:

資料庫資訊

最後我們通過Postman測試資料:

年紀剛好
年紀太小
年紀太大
後臺錯誤

這樣,我們就將Result的JSON資料傳遞到了前臺,而前臺就會根據錯誤程式碼和提示及資訊進行相應處理。