Springboot-统一异常处理

tech2022-09-04  117

前言:有没有不需要跟Controller耦合,也可以将定义的 异常处理器 应用到所有控制器呢?所以注解@ControllerAdvice出现了,简单的说,该注解可以把异常处理器应用到所有控制器,而不是单个控制器。借助该注解,我们可以实现:在独立的某个地方,比如单独一个类,定义一套对各种异常的处理机制,然后在类的签名加上注解@ControllerAdvice,统一对 不同阶段的、不同异常 进行处理。这就是统一异常处理的原理。

1.常见异常介绍

在程序中大致分为两大异常:

Error:系统级别的错误,程序代码无法处理的,发生这些错误发生时,JVM一般会选择线程终止退出,它表示程序在运行期间出现了十分严重、不可恢复的错误,应用程序只能中止运行。程序中显示调用System.exit(1);也会退出虚拟机。Exception:程序级别的异常,Exception下也分为两种,运行时异常(RunTimeException)和检查异常(CheckedException) 以下是常用Exception:

2.统一处理异常思想

编码时在其他业务逻辑层只需要将异常向调用层抛出即可,即:dao -> service -> controler,最后异常到controller层时,controller将异常交给异常处理器处理,这样就能统一管理异常,使用AOP记录详细一场,@ControllerAdvice注解去处理异常,大大的与代码直接进行解耦。

3.实现统一处理异常

/** * FileNome: BaseExceptionHandler * Author: 劉勇 * Date: 2020/7/15 14:49 * Description: 公共处理异常类 * History: */ package com.cserver.saas.system.module.estate.iwork.config; import com.cserver.saas.system.module.estate.iwork.util.JsonResult; import com.cserver.saas.system.module.estate.iwork.util.ResponseStatus; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class BaseExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity<String> handler(Exception e) { System.out.println("处理异常"); JsonResult jsonResult = new JsonResult(); jsonResult.setStatus(ResponseStatus.ERROR); jsonResult.setMessage("异常消息"); jsonResult.setData(e.getMessage()); return new ResponseEntity<>(jsonResult.toJson(), HttpStatus.OK); } }

这样前端接收统一的异常格式。

最新回复(0)