Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
  • Spring常见面试题
  • Spring常用注解与接口
  • 容器与Bean
  • AOP
  • Spring事务
  • Spring中的设计模式
  • 手撸Spring

  • 事务嵌套
  • 事件监听器
  • Spring自定义异常
    • 自定义异常
  • Spring
Nreal
2024-04-02
目录

Spring自定义异常

# 自定义异常

  1. 创建自定义异常类;

    继承自RuntimeException或其子类;

    public class CustomException extends RuntimeException {
    
        public CustomException() {
            super();
        }
    
        public CustomException(String message) {
            super(message);
        }
    
        public CustomException(String message, Throwable cause) {
            super(message, cause);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  2. Spring控制器处理异常;

    @ControllerAdvice表示全局异常处理器;

    @ExceptionHandler处理自定义异常;

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(CustomException.class)
        public ResponseEntity<String> handleCustomException(CustomException ex) {
            return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
事件监听器

← 事件监听器

Theme by Vdoing | Copyright © 2021-2024
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式