能不能自己做视频网站,余姚做网站设计的,wordpress x theme,做家装的有没有网站可以找工作目录 统一异常处理一. 概念二. 全局异常处理三. 处理特定异常 统一异常处理
一. 概念
其实统一异常是运用了AOP#xff08;对某一类事情的集中处理#xff09;的思维#xff0c;简单概括就是在我们进行前后端数据交互的时候#xff0c;抛出的任何的异常都能够自动捕获然后… 目录 统一异常处理一. 概念二. 全局异常处理三. 处理特定异常 统一异常处理
一. 概念
其实统一异常是运用了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
ResponseBodypublic class ErrorAdvice {/*** 全局异常处理*/ExceptionHandlerpublic 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
ControllerAdvicepublic class ErrorAdvice {ExceptionHandlerpublic Object handler(Exception e) {return Result.fail(e.getMessage());}ExceptionHandlerpublic Object handler(NullPointerException e) {return Result.fail(发⽣NullPointerException:e.getMessage());}ExceptionHandlerpublic Object handler(ArithmeticException e) {return Result.fail(发⽣ArithmeticException:e.getMessage());}}当有多个异常通知时匹配顺序为当前类及其⼦类向上依次匹配
进行统一异常处理的目的就是在异常发生时尽可能地减少破坏妥善处理而不去影响其他部分程序的运行