Spring Boot——十、Spring Boot 中的异常处理与单元测试

1 异常处理

1.1自定义错误页面

SpringBoot 默认的处理异常的机制:SpringBoot默认的已经提供了一套处理异常的机制。 一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 SpringBoot 中提供了一个 名为 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信 息。

如 果 我 们 需 要 将 所 有 的 异 常 同 一 跳 转 到 自 定 义 的 错 误 页 面 , 需 要 再 src/main/resources/templates 目录下创建 error.html 页面。注意:页面名称必须叫 error

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>错误页面</title>
</head>
<body>
出错了!请与管理员联系!<span th:text="${error}"></span>
</body>
</html>

1.2通过@ExceptionHandler 注解处理异常
在控制器中增加处理异常的方法,方法前增加注解@ExceptionHandler(异常名称)。作用范围,一个控制器。

1.3通过@ControllerAdvice 与@ExceptionHandler 注解处理异 常
写一个全局异常处理器,类前面增加注解@ControllerAdvice,方法前面增加注解@ExceptionHandler(异常名称)。作用范围,所有控制器中的异常都将被捕获。

注意:返回值是ModelAndView

@ControllerAdvice
public class GlobalException {
    @ExceptionHandler({ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("error",e);
        modelAndView.setViewName("firstError");
        return modelAndView;
    }
    @ExceptionHandler({NullPointerException.class})
    public ModelAndView nullPointerExceptionHandler(Exception e){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("error",e.toString());
        modelAndView.setViewName("secondError");
        return modelAndView;
    }
}

1.4通过 SimpleMappingExceptionResolver 对象处理异常
上面的全局异常控制器处理范围是所有控制器,但对于每一类异常都要针对性的写一个处理该类异常的方法。通过使用SimpleMappingExceptionResolver 可以实现一个方法处理所有类型的异常。缺点是异常详细内容不知道是什么。

package com.bjsxt.springbootjdbc.exception;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.Properties;

@Configuration
public class GlobalException2 {
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties=new Properties();
        properties.put("java.lang.NullPointerException","secondError");
        properties.put("java.lang.ArithmeticException","firstError");
        resolver.setExceptionMappings(properties);
        return resolver;
    }
}

1.5通过自定义 HandlerExceptionResolver 对象处理异常
处理范围:所有控制器中的异常
编写处理异常的方法数量:所有类型异常可以被一个方法处理
是否能获得异常信息:是

需要实现一个 HandlerExceptionResolver 接口。

package com.bjsxt.springbootjdbc.exception;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class GlobalException3 implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        if(e instanceof NullPointerException){
            mv.setViewName("error5");
        }
        if(e instanceof ArithmeticException){
            mv.setViewName("error6");
        }
        mv.addObject("error",e.toString());
        return mv;
    }
}

2 Spring Boot 整合 Junit 单元测试

2.1修改 POM 文件添加 Test 启动器

junit-vintage-engine 提供了 Junit3 与 Junit4 的运 行平台,但是不用他,所以依赖中有exclusion标签排除。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2.2编写测试代码

package com.bjsxt.springbootjdbc;

import com.bjsxt.springbootjdbc.pojo.Users;
import com.bjsxt.springbootjdbc.service.UsersService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringbootjdbcApplicationTests {
    @Autowired
    UsersService usersService;
    @Test
    void contextLoads() {
    }
    @Test
    void testQuery(){
        List<Users> users = this.usersService.queryAllUsers();
        for(Users u:users){
            System.out.println(u);
        }
    }
}

运行结果:
测试代码:
在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值