【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());
	}

}

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

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

  • 77
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 114
    评论
评论 114
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从零开始的-CodeNinja之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值