SpringBoot 统一异常处理

devtools/2025/3/13 0:27:34/
  1. 首先定义一个统一管理所有异常的类,加上注解@RestControllerAdvice
  2. 定义处理不同异常的方法,加上注解 @ExceptionHandler
  3. java">@RestControllerAdvice
    public class GlobalExceptionHandler
    {private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);/*** 权限码异常*/@ExceptionHandler(NotPermissionException.class)public AjaxResult handleNotPermissionException(NotPermissionException e, HttpServletRequest request){String requestURI = request.getRequestURI();log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());return AjaxResult.error(HttpStatus.FORBIDDEN, "没有访问权限,请联系管理员授权");}/*** 角色权限异常*/@ExceptionHandler(NotRoleException.class)public AjaxResult handleNotRoleException(NotRoleException e, HttpServletRequest request){String requestURI = request.getRequestURI();log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());return AjaxResult.error(HttpStatus.FORBIDDEN, "没有访问权限,请联系管理员授权");}/*** 请求方式不支持*/@ExceptionHandler(HttpRequestMethodNotSupportedException.class)public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request){String requestURI = request.getRequestURI();log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());return AjaxResult.error(e.getMessage());}/*** 业务异常*/@ExceptionHandler(ServiceException.class)public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request){log.error(e.getMessage(), e);Integer code = e.getCode();return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());}/*** 请求路径中缺少必需的路径变量*/@ExceptionHandler(MissingPathVariableException.class)public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request){String requestURI = request.getRequestURI();log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));}/*** 请求参数类型不匹配*/@ExceptionHandler(MethodArgumentTypeMismatchException.class)public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request){String requestURI = request.getRequestURI();String value = Convert.toStr(e.getValue());if (StringUtils.isNotEmpty(value)){value = EscapeUtil.clean(value);}log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), value));}/*** 拦截未知的运行时异常*/@ExceptionHandler(RuntimeException.class)public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request){String requestURI = request.getRequestURI();log.error("请求地址'{}',发生未知异常.", requestURI, e);return AjaxResult.error(e.getMessage());}/*** 系统异常*/@ExceptionHandler(Exception.class)public AjaxResult handleException(Exception e, HttpServletRequest request){String requestURI = request.getRequestURI();log.error("请求地址'{}',发生系统异常.", requestURI, e);return AjaxResult.error(e.getMessage());}/*** 自定义验证异常*/@ExceptionHandler(BindException.class)public AjaxResult handleBindException(BindException e){log.error(e.getMessage(), e);String message = e.getAllErrors().get(0).getDefaultMessage();return AjaxResult.error(message);}/*** 自定义验证异常*/@ExceptionHandler(MethodArgumentNotValidException.class)public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e){log.error(e.getMessage(), e);String message = e.getBindingResult().getFieldError().getDefaultMessage();return AjaxResult.error(message);}/*** 内部认证异常*/@ExceptionHandler(InnerAuthException.class)public AjaxResult handleInnerAuthException(InnerAuthException e){return AjaxResult.error(e.getMessage());}/*** 演示模式异常*/@ExceptionHandler(DemoModeException.class)public AjaxResult handleDemoModeException(DemoModeException e){return AjaxResult.error("演示模式,不允许操作");}
    }


http://www.ppmy.cn/devtools/166628.html

相关文章

2025最新群智能优化算法:云漂移优化(Cloud Drift Optimization,CDO)算法求解23个经典函数测试集,MATLAB

一、云漂移优化算法 云漂移优化(Cloud Drift Optimization,CDO)算法是2025年提出的一种受自然现象启发的元启发式算法,它模拟云在大气中漂移的动态行为来解决复杂的优化问题。云在大气中受到各种大气力的影响,其粒子的…

20、组件懒加载

组件懒加载,也被称为异步组件加载,是一种在 Vue 项目中提升性能的重要技术手段。下面从概念、实现原理、使用场景、实现方式几个方面详细介绍: 概念 在传统的 Vue 项目里,当应用启动时,所有的组件代码都会被一次性加…

中小企业Windows双因素认证的“轻量化”安全解决方案

一、为何中小企业亟需Windows双因素认证? 在数字化转型浪潮下,中小企业面临的安全威胁与大型企业无异,但预算和IT资源却更为有限。传统静态密码的脆弱性(如弱口令、暴力破解、钓鱼攻击)已成为企业数据泄露的主要入口。…

Spring Boot 项目中 `Query` 后缀对象的放置位置

在 Spring Boot 项目中,带有 Query 后缀的查询对象通常属于请求参数或数据传输层,推荐将其放置在以下位置之一: 推荐目录结构 src└── main└── java└── com└── example├── controller├── dto # ✅ 推荐&#x…

万字技术指南STM32F103C8T6 + ESP8266-01 连接 OneNet 平台 MQTT/HTTP

此博客为一份详细的指南,涵盖 STM32F103C8T6 通过 ESP8266-01 连接 OneNet 平台,并使用 MQTT/HTTP 进行数据通信的完整流程。这份文档包括: OneNet 平台的介绍与功能概览在 OneNet 上创建和配置设备的方法STM32CubeIDE 的开发环境搭建ESP826…

计算机视觉算法实战——昆虫识别检测(主页有源码)

✨个人主页欢迎您的访问 ✨期待您的三连 ✨ ✨个人主页欢迎您的访问 ✨期待您的三连 ✨ ✨个人主页欢迎您的访问 ✨期待您的三连✨ ​ ​​​ 1. 引言 昆虫识别检测是计算机视觉领域的一个重要研究方向,旨在通过图像分析和机器学习技术自动识别和检测昆虫的种类及…

Android WebSocket工具类:重连、心跳、消息队列一站式解决方案

依赖库 使用 OkHttp 的WebSocket支持。 在 build.gradle 中添加依赖: implementation com.squareup.okhttp3:okhttp:4.9.3WebSocket工具类实现 import okhttp3.*; import android.os.Handler; import android.os.Looper; import android.util.Log;import java.ut…

MySQL数据库的相关语句

数据库的操作(CURD) 创建数据库(重点) 查看数据库(重点) show databases; ‐‐ 查看所有的数据库use 数据库名称;(*****) ‐‐ 使用数据库show create database 数据库名称; ‐‐ 查询数据库的创建的信息s…