【SpringBoot3】全局异常处理

news2024/9/21 16:37:48

【SpringBoot3】全局异常处理

  • 一、全局异常处理器
    • step1:创建收入数字的页面
    • step2:创建控制器,计算两个整数相除
    • step3:创建自定义异常处理器
    • step5:创建给用提示的页面
    • step6:测试输入(10/0)
  • 二、BeanValidator 异常处理
    • step1:添加 JSR-303 依赖
    • step2:创建 Bean 对象,属性加入 JSR-303 注解
    • step3:Controlller 接收请求
    • step4:创建异常处理器
    • step5:测试

在 Controller 处理请求过程中发生了异常,DispatcherServlet 将异常处理委托给异常处理器(处理异常的类)。实现 HandlerExceptionResolver 接口的都是异常处理类。
项目的异常一般集中处理,定义全局异常处理器。在结合框架提供的注解,诸如:@ExceptionHandler,@ControllerAdvice ,@RestControllerAdvice 一起完成异常的处理。@ControllerAdvice 与@RestControllerAdvice 区别在于:@RestControllerAdvice 加了@RepsonseBody。

一、全局异常处理器

  • 需求:应用计算两个数字相除,当用户被除数为 0 ,发生异常。使用自定义异常处理器代替默认的异常处理程序

step1:创建收入数字的页面

  • 在 static 目录下创建 input.html , static 目录下的资源浏览器可以直接访问
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="divide" method="post">&nbsp;&nbsp;&nbsp;数:<input type="text" name="n1"> <br/>
  被除数:<input type="text" name="n2"> <br/>
  <input type="submit" value="计算">
</form>
</body>
</html>

在这里插入图片描述

step2:创建控制器,计算两个整数相除

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NumberController {
    @PostMapping("/divide")
    public String some(Integer n1,Integer n2){
        int result = n1/n2;
        return "n1/n2 = " + result;
    }
}

step3:创建自定义异常处理器

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//控制器增强
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({ArithmeticException.class})
    public String handlerArtithmecticException(ArithmeticException e, Model model){
        String error = e.getMessage();
        model.addAttribute("error",error);
        return "exp";
    }

/*    @ExceptionHandler({ArithmeticException.class})
    @ResponseBody
    public Map<String,String> handlerArtithmecticException(ArithmeticException e){
        Map<String,String> errors = new HashMap<>();
        errors.put("msg",e.getMessage());
        errors.put("tips","被除数不能为0");
        return errors;
    }*/
}

step5:创建给用提示的页面

  • 在 resources/templates/ 创建 exp.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>显示异常信息:<div th:text = "${error}"></div> </h3>
</body>
</html>

step6:测试输入(10/0)

在这里插入图片描述
在这里插入图片描述

二、BeanValidator 异常处理

使用 JSR-303 验证参数时,我们是在 Controller 方法,声明BindingResult 对象获取校验结果。Controller 的方法很多,每个方法都加入 BindingResult 处理检验参数比较繁琐。 校验参数失败抛出异常给框架,异常处理器能够捕获到 MethodArgumentNotValidException,它是 BindException 的子类。
在这里插入图片描述
BindException 异常实现了 BindingResult 接口,异常类能够得到 BindingResult 对象,进一步获取 JSR303 校
验的异常信息。

  • 需求:全局处理 JSR-303 校验异常

step1:添加 JSR-303 依赖

在这里插入图片描述

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
   </dependency>

step2:创建 Bean 对象,属性加入 JSR-303 注解

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import org.hibernate.validator.constraints.Range;

@Data
public class OrderVO {

    @NotBlank(message = "订单名称不能为空")
    private String name;
    @NotNull(message = "商品必须有数量")
    @Range(min = 1,max = 99,message = "一个订单商品数量在{min} -- {max}")
    private Integer amount;

    @NotNull(message = "用户不能为空")
    @Min(value = 1,message = "从1开始")
    private Integer userId;
}

step3:Controlller 接收请求

import com.bjpowernode.exp.vo.OrderVO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

    @PostMapping("/order/new")
    public String createOrder(@Validated @RequestBody OrderVO orderVO){
        return "订单信息:" + orderVO.toString();
    }
}

step4:创建异常处理器

import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//控制器增强
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({ArithmeticException.class})
    public String handlerArtithmecticException(ArithmeticException e, Model model){
        String error = e.getMessage();
        model.addAttribute("error",error);
        return "exp";
    }

/*    @ExceptionHandler({ArithmeticException.class})
    @ResponseBody
    public Map<String,String> handlerArtithmecticException(ArithmeticException e){
        Map<String,String> errors = new HashMap<>();
        errors.put("msg",e.getMessage());
        errors.put("tips","被除数不能为0");
        return errors;
    }*/

    //处理JSR303 验证参数的异常
    //@ExceptionHandler({BindException.class})
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Map<String,Object> handlerJSR303Exception(MethodArgumentNotValidException e){
        System.out.println("=============JSR303===========");
        Map<String,Object> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        if(result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (int i = 0; i < fieldErrors.size(); i++) {
                FieldError fieldError = fieldErrors.get(i);
                map.put(i + "-" + fieldError.getField(), fieldError.getDefaultMessage());
            }
        }
        return map;
    }
}
  • 核心代码:
    在这里插入图片描述

step5:测试

POST http://localhost:8080/order/new
Content-Type: application/json

{
  "name": "每日订单",
  "amount": 0,
  "userId": 0
}

在这里插入图片描述
显示:
{
“1-amount”: “一个订单商品数量在1 – 99”,
“0-userId”: “从1开始”
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1941067.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

TCP/IP网络模型详解

在计算机网络领域&#xff0c;网络模型通常指的是 OSI&#xff08;Open Systems Interconnection&#xff09;参考模型或 TCP/IP&#xff08;Transmission Control Protocol/Internet Protocol&#xff09;模型。这些模型描述了网络中数据传输的层次结构&#xff0c;便于理解和…

ROS2从入门到精通2-3:详解机器人3D物理仿真Gazebo与案例分析

目录 0 专栏介绍1 什么是Gazebo?2 Gazebo架构2.1 Gazebo前后端2.2 Gazebo文件格式2.3 Gazebo环境变量3 Gazebo安装与基本界面4 搭建自己的地图4.1 编辑地图4.2 保存地图4.3 加载地图5 常见问题0 专栏介绍 本专栏旨在通过对ROS2的系统学习,掌握ROS2底层基本分布式原理,并具有…

【面试八股文】计算机操作系统

参考&#xff1a;大佬图解文章 → 小林coding 简介&#xff1a;之前在学习小林大佬的八股文时&#xff0c;摘录了一些个人认为比较重要的内容&#xff0c;方便后续自己复习。【持续更新ing ~&#x1f4af;】 注&#xff1a;加五角星标注的&#xff0c;是当前掌握不牢固的&…

WEB攻防-通用漏洞-SQL注入-MYSQL-union一般注入

前置知识 MySQL5.0以后存放一个默认数据库information_schemaschemata表存放该用户创建的所有库名&#xff0c;schemata. schema_name字段存放库名tables表存放该用户创建的所有库名和表明&#xff0c;tables.table_schema字段存放库名&#xff0c;tables.table_name存放表名co…

Elastic 及阿里云 AI 搜索 Tech Day 将于 7 月 27 日在上海举办

活动主题 面向开发者的 AI 搜索相关技术分享&#xff0c;如 RAG、多模态搜索、向量检索等。 活动介绍 参加 Elastic 原厂与阿里云联合举办的 Generative AI 技术交流分享日。借助 The Elastic Search AI Platform&#xff0c; 使用开放且灵活的企业解决方案&#xff0c;以前所…

基于YOLO8的目标检测系统:开启智能视觉识别之旅

文章目录 在线体验快速开始一、项目介绍篇1.1 YOLO81.2 ultralytics1.3 模块介绍1.3.1 scan_task1.3.2 scan_taskflow.py1.3.3 target_dec_app.py 二、核心代码介绍篇2.1 target_dec_app.py2.2 scan_taskflow.py 三、结语 在线体验 基于YOLO8的目标检测系统 基于opencv的摄像头…

Spring Cloud GateWay(4.1.4)

介绍 该项目提供了一个建立在 Spring 生态系统之上的 API 网关&#xff0c;包括&#xff1a;Spring 6、Spring Boot 3 和 Project Reactor。Spring Cloud Gateway 旨在提供一种简单而有效的方法来路由到 API&#xff0c;并为其提供跨领域关注点&#xff0c;例如&#xff1a;安…

华清数据结构day3 24-7-18

基于昨天代码增加增删改查功能 zy.h #ifndef ZY_H #define ZY_H #define MAX 100 //最大容量 //定义学生类型 struct Stu {char name[20];int age;double score; }; //定义班级类型 struct Class {struct Stu student[MAX]; //存放学生的容器int size; //实际…

【Git】(基础篇五)—— Git进阶

Git进阶 之前关于本地和远程仓库的各种操作都已经非常基础了&#xff0c;本文介绍git的一些进阶使用和设置 用户名和邮箱 之前介绍的每一次提交(commit) 都会产生一条日志(log) 信息&#xff0c;这条日志信息不仅会记录提交信息&#xff0c;还会记录执行提交操作的这个用户的…

【QAC】分布式部署下其他机器如何连接RLM

1、 文档目标 解决分布式部署下其他机器如何连接RLMLicense管理器。 2、 问题场景 分布式部署下QAC要在其他机器上单独运行扫描&#xff0c;必须先连接RLMLicense管理器&#xff0c;如何连接&#xff1f; 3、软硬件环境 1、软件版本&#xff1a;HelixQAC23.04 2、机器环境…

ClusterIP、NodePort、LoadBalancer 和 ExternalName

Service 定义 在 Kubernetes 中&#xff0c;由于Pod 是有生命周期的&#xff0c;如果 Pod 重启它的 IP 可能会发生变化以及升级的时候会重建 Pod&#xff0c;我们需要 Service 服务去动态的关联这些 Pod 的 IP 和端口&#xff0c;从而使我们前端用户访问不受后端变更的干扰。 …

SpringBoot Security OAuth2实现单点登录SSO(附源码)

文章目录 基础概念1. 用户认证2. 单点登录&#xff08;SSO&#xff09;3. 授权管理4. 安全性和配置 逻辑实现配置认证服务器配置Spring Security两个客户端 页面展示本篇小结 更多相关内容可查看 附源码地址&#xff1a;https://gitee.com/its-a-little-bad/SSO.git 基础概念 …

HarmonyOS 状态管理(一)

1. HarmonyOS 状态管理 1.1. 说明 官方文档&#xff08;https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-state-management-V5&#xff09; 1.1.1. 状态管理&#xff08;V1稳定版&#xff09; 状态管理&#xff08;V1稳定版&#xff09;提供了多种…

90+ Python 面试问答(2024 版)

90+ Python 面试问答(2024 版) 一、介绍 欢迎来到准备数据科学工作面试的第一步。这里有一个全面而广泛的 Python 面试问题和答案列表,可帮助您在面试中取得好成绩并获得理想的工作!Python 是一种解释型通用编程语言,由于其在人工智能 (AI) 中的使用,如今需求量很大。…

python大小写转换、驼峰大小写转换

一 大小写转换 1第1个单词的首字母大写 capitalize() 2每个单词的首字母大写 title() 3所有字母大小写转换 swapcase() 代码示例 texttoday is sundaYprint(text.capitalize()) # 仅第1个单词的首字母大写 print(text.title()) # 每个单词的首字母大写 print(text.swapcase…

Vue 多选下拉框+下拉框列表中增加标签

1、效果图 2、代码部分 &#xff08;1&#xff09;代码 <el-select class"common-dialog-multiple multipleSelectStyle" change"clusterListChange" v-model"form.clusterId" placeholder"请先选择" multiple filterable defaul…

【BUG】已解决:AttributeError: ‘str‘ object has no attribute ‘read‘

AttributeError: ‘str‘ object has no attribute ‘read‘ 目录 AttributeError: ‘str‘ object has no attribute ‘read‘ 【常见模块错误】 【解决方案】 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998https://bbs.csdn.net/topics/617804998 欢迎来到我的主…

(7) cmake 编译C++程序(二)

文章目录 概要整体代码结构整体代码小结 概要 在ubuntu下&#xff0c;通过cmake编译一个稍微复杂的管理程序 整体代码结构 整体代码 boss.cpp #include "boss.h"Boss::Boss(int id, string name, int dId) {this->Id id;this->Name name;this->DeptId …

error C2011: “sockaddr_in”:“struct”类型重定义的修改办法

问题 windows.h和winsock2.h存在有类型重定义,往往体现在头文件包含winsock2.h和windows.h时出现编译错误: error C2011: “sockaddr_in”:“struct”类型重定义 2>D:\Windows Kits\10\Include\10.0.22000.0\shared\ws2def.h(442,5): error C2143: 语法错误: 缺少“}”(…

为什么大家都想学大模型?一文揭秘!

小编只是普通的汽车软件工程师&#xff0c;想了解人工智能&#xff0c;又感觉好遥远&#xff0c;仔细的看了半天&#xff0c;就一个想法 好好拥抱AI吧。真的好强。 相比之下&#xff0c;Autosar 是个 der 啊。。。。 人工智能基础概念全景图 AI -> 机器学习 机器学习 ->…