【Spring Boot】统一异常处理

目录
  • 统一异常处理
    • [一. 概念](#一. 概念)
    • [二. 全局异常处理](#二. 全局异常处理)
    • [三. 处理特定异常](#三. 处理特定异常)

统一异常处理

一. 概念

其实统一异常是运用了AOP(对某一类事情的集中处理)的思维,简单概括就是在我们进行前后端数据交互的时候,抛出的任何的异常都能够自动捕获然后抛出,不用程序员在敲代码时格外关注try catch语句。

其实统一异常处理非常简单,在实现时要加入类注解@ControllerAdvice(这是一个表示控制通知的注解,在接下来的统一异常处理也要运用到),并且有一点与统一数据返回不同的是,统一异常处理需要加上类注解@ResponseBody来确认返回的数据类型,然后在类中要进行捕获异常的方法上加上注解@ExceptionHandle即可。

二. 全局异常处理

处理全局异常代码如下:

复制代码
import com.example.demo.model.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


 
@ControllerAdvice
@ResponseBody

public class ErrorAdvice {

	/**
	 * 全局异常处理
	 */
	@ExceptionHandler
	public Object handler(Exception e) {
		return Result.fail(e.getMessage());
	}
	
}

这样程序抛出异常的时候,就会被该异常处理方法所捕获,并且返回统一异常处理的结果(JSON格式)!

三. 处理特定异常

处理特定异常代码如下:

复制代码
import com.example.demo.model.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ResponseBody
@ControllerAdvice

public class ErrorAdvice {

	@ExceptionHandler
	public Object handler(Exception e) {
		return Result.fail(e.getMessage());
	}

	@ExceptionHandler
	public Object handler(NullPointerException e) {
		return Result.fail("发?NullPointerException:"+e.getMessage());
	}

	@ExceptionHandler
	public Object handler(ArithmeticException e) {
		return Result.fail("发?ArithmeticException:"+e.getMessage());
	}

}

当有多个异常通知时,匹配顺序为当前类及其类向上依次匹配

进行统一异常处理的目的就是在异常发生时,尽可能地减少破坏,妥善处理,而不去影响其他部分程序的运行

相关推荐
万少1 天前
我是如何使用 Trae IDE 完成《流碧卡片》项目的完整记录
前端·后端·ai编程
ituff1 天前
微软认证考试又免费了
后端·python·flask
倔强的石头_1 天前
openGauss赋能智能客服:AI时代的企业服务变革
后端
likuolei1 天前
XML 元素 vs. 属性
xml·java·开发语言
自不量力的A同学1 天前
Spring Boot 4.0.0 正式发布
java·spring boot·后端
d***29241 天前
【spring】Spring事件监听器ApplicationListener的使用与源码分析
java·后端·spring
5***b971 天前
解决报错net.sf.jsqlparser.statement.select.SelectBody
java
q***95221 天前
Tomcat下载,安装,配置终极版(2024)
java·tomcat
2***d8851 天前
详解tomcat中的jmx监控
java·tomcat
无敌最俊朗@1 天前
Qt事件循环队列剖析!!!
java