Spring boot 中的 统一异常处理

用 spring boot 开发 Java Web 项目,在 Controller 层处理用户提交的请求时,难免会遇到异常。因此学习 统一的处理 Controller 层中出现的异常是有必要。

项目下载


统一异常处理:

  1. 全局异常处理
  2. 特定异常处理
  3. 自定义异常处理

主要代码

测试的 Controller

package top.leeti.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.leeti.entity.R;
import top.leeti.exception.MyException;

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

@RestController
public class IndexController {
    
    

    @ApiOperation("正常测试的 uri")
    @GetMapping("test")
    public R test() {
    
    
        return R.ok();
    }

    @ApiOperation("测试全局异常的 uri")
    @GetMapping("globalError")
    public R testGlobalError() {
    
    
        // 抛出: IndexOutOfBoundsException
        // 并被全局异常处理器捕获
        List<String> list = new ArrayList<>(Arrays.asList("a"));
        list.get(3);

        return R.ok();
    }

    @ApiOperation("测试特定异常的 uri")
    @GetMapping("specialError")
    public R testSpecialError() {
    
    
        // 抛出: ArithmeticException
        // 并被 ArithmeticException 异常处理器捕获
        int ans = 9 / 0;

        return R.ok();
    }

    @ApiOperation("测试自定义异常的 uri")
    @GetMapping("mineError")
    public R testMineError() throws MyException {
    
    
        // 抛出: MyException
        // 并被 MyException 异常处理器捕获
        throw new MyException();
    }
}

测试的异常处理器

package top.leeti.handler;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.leeti.entity.R;
import top.leeti.exception.MyException;

@RestControllerAdvice
public class TestExceptionHandler {
    
    

    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
    
    
        e.printStackTrace();
        return R.error().message("执行出现了全局异常处理......");
    }

    @ExceptionHandler(ArithmeticException.class)
    public R error(ArithmeticException e) {
    
    
        e.printStackTrace();
        return R.error().message("执行出现了 ArithmeticException 异常处理......");
    }

    @ExceptionHandler(MyException.class)
    public R error(MyException e) {
    
    
        e.printStackTrace();
        return R.error().message("执行出现了 MyException 异常处理......");
    }
}

开始测试

启动项目

依次输入 url,并观察返回的结果:

  • http://localhost:8000/test
    在这里插入图片描述
  • http://localhost:8000/globalError
    在这里插入图片描述
  • http://localhost:8000/specialError
    在这里插入图片描述
  • http://localhost:8000/mineError
    在这里插入图片描述

至此,Spring boot 中的 统一异常处理 结束了。

需要说明的是:

统一异常处理的原理是 spring 的 ()面向切面编程
全局异常能匹配没有特殊说明(即单独处理的异常)的全部异常。

猜你喜欢

转载自blog.csdn.net/Snakehj/article/details/113712326
今日推荐