【Spring boot 全局异常捕捉】

news/2024/7/7 22:42:16
Spring boot 全局异常捕捉
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢?
新建一个类 GlobalDefaultExceptionHandler,
在 class 注解上@ControllerAdvice,
@C ONTROLLER A DVICE :即把@C ONTROLLER A DVICE 注解内部使用@E XCEPTION H ANDLER 、@I NIT B INDER
@M ODEL A TTRIBUTE 注解的方法应用到所有的 @R EQUEST M APPING 注解的方法。非常简单,不过只有当使用
@E XCEPTION H ANDLER 最有用,另外两个用处不大。
在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下
package com.hpit.base.exception;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
publicclass GlobalDefaultExceptionHandler {
@ExceptionHandler (value = Exception. class )
publicvoid defaultErrorHandler(HttpServletRequest req , Exception e ) {
// // If the exception is annotated with @ResponseStatus rethrow it and let
// // the framework handle it - like the OrderNotFoundException example
// // at the start of this post.
// // AnnotationUtils is a Spring Framework utility class.
// if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
// throw e;
//
// // Otherwise setup and send the user to a default error-view.
// ModelAndView mav = new ModelAndView();
// mav.addObject("exception", e);
关注公众号 Java 核⼼技术获取更多教程 10 / 108
// mav.addObject("url", req.getRequestURL());
// mav.setViewName(DEFAULT_ERROR_VIEW);
// return mav;
// 打印异常信息:
e .printStackTrace();
System. out .println( "GlobalDefaultExceptionHandler.defaultErrorHandler()" );
/*
* 返回 json 数据或者 String 数据:
* 那么需要在方法上加上注解: @ResponseBody
* 添加 return 即可。
*/
/*
* 返回视图:
* 定义一个 ModelAndView 即可,
* 然后 return;
* 定义视图文件 ( 比如: error.html,error.ftl,error.jsp);
*
*/
}
}
com.hpit.test.web.DemoController 加入方法:
@RequestMapping ( "/zeroException" )
publicint zeroException(){
return 100/0;
}
访问: http://127.0.0.1:8080/zeroException 这个方法肯定是抛出异常的 , 那么在控制台就可以看到我们全局捕捉
的异常信息了
5 Spring boot JPA 连接数据库
在任何一个平台都逃离不了数据库的操作,那么在 spring boot 中怎么接入数据库呢?
很简单,我们需要在 application.properties 进行配置一下,application.properties 路径是 src/main/resources 下,
对于 application.properties 更多的介绍请自行百度进行查找相关资料进行查看,在此不进行过多的介绍,以下只
是 mysql 的配置文件。
大体步骤:
(1)在 application.properties 中加入 datasouce 的配置
关注公众号 Java 核⼼技术获取更多教程 11 / 108
(2)在 pom.xml 加入 mysql 的依赖。
(3)获取 DataSouce 的 Connection 进行测试。
src/main/resouces/application.properties:
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active= 20
spring.datasource.max-idle= 8
spring.datasource.min-idle= 8
spring.datasource.initial-size= 10
pom.xml 配置:
< dependency >
< groupId > mysql </ groupId >
< artifactId > mysql-connector-java </ artifactId >
</ dependency >
到此相关配置就 ok 了,那么就可以在项目中进行测试了,我们可以新建一个 class Demo 进行测试,实体类创建
完毕之后,我们可能需要手动进行编写建表语句,这时候我们可能就会想起 Hibernate 的好处了。

http://lihuaxi.xjx100.cn/news/141997.html

相关文章

浅谈线程池的拓容、判断、限速技巧

本文主要分享线程池的动态拓容、判断执行任务执行完毕、线程任务提交速度限制三个线程池使用技巧。 线程池动态拓容 创建线程池 ThreadPoolExecutor taskExecutor new ThreadPoolExecutor(8, 64, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(256), new ThreadFa…

Java Spring Cloud XXIII 之 配置中心

Java Spring Cloud XXIII 之 配置中心 配置中心 1.配置中心简介 所谓配置中心:将项目需要的配置信息保存在配置中心,需要读取时直接从配置中心读取,方便配置管理的微服务工具 我们可以将部分yml文件的内容保存在配置中心 一个微服务项目有很多子模块,这些子模块可能在不同…

中国及全球LNG液化天然气行业发展趋势分析告

智研瞻产业研究院专注于中国产业经济情报及研究&#xff0c;目前主要提供的产品和服务包括传统及新兴行业研究、商业计划书、可行性研究、市场调研、专题报告、定制报告等。涵盖文化体育、物流旅游、健康养老、生物医药、能源化工、装备制造、汽车电子、农林牧渔等领域&#xf…

hyperf 模型批量更新数据

使用hyperf框架没有批量更新方法&#xff0c;只能自己拼接SQL语句进行批量跟你更新 封装一个SQL句更新方法 //批量更新public function updateBatch($multipleData []){try {$tableName Db::getTablePrefix() . table;// 获取到数据里面的所有字段名$firstRow current($m…

Linux下NANDFLASH probe函数分析

本文记录一下自己平台上NANDFLASH驱动的执行流程。 驱动入口&#xff1a; module_platform_driver(ali_nand_driver); module_platform_driver是一个宏&#xff0c;位于kernel根目录下include/linux/platform_device.h,其展开如下: #define module_platform_driver(__platfo…

Java中的容器(二) 双例集合

容器(二) 双例集合 1、Map接口介绍 Map中不能包含重复的Key&#xff0c;但可以包含重复的Value。 Map中的常用方法 put方法&#xff1a;key不存在时返回空&#xff0c;key存在时更新value&#xff0c;并返回旧的value。 2、HashMap容器类 通过KeySet获取元素 Set<String…

VectorDraw开发者框架(VDF)

VectorDraw开发者框架(VDF) VectorDraw Developer Framework(VDF)是一个易于创建、管理和打印2D和3D图纸的组件。VectorDraw对象公开了与最常见的矢量格式和其他CAD对象兼容的方法和属性。它支持10多种矢量格式和多种光栅格式。VectorDrawDeveloperFramework(VDF)是完全面向对象…

arraybuffer 转json

场景后端返回的数据是arraybuffer 类型&#xff0c;请求成功下载excel&#xff0c;失败弹出错误原因 <script setup lang"ts"> import { ElMessage} from element-plus; // 下载; const exportData async (fileName: string) > {const res await downloa…