全局参数、异常处理

简介: 全局参数、异常处理

1、创建全局处理类

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * @Description: 全局参数处理
 * @Author: Guo.Yang
 * @Date: 2022/10/10/20:56
 */
@RestControllerAdvice
public class GlobalParametersValidation {
    /**
     * 全局参数处理
     * 控制器注册一个属性编辑器
     * 所谓的属性编辑器可以理解就是帮助我们完成参数绑定。
     * (控制器获取的参数,进行参数的前置处理)
     * @param webDataBinder
     */
    @InitBinder
    public void initData(WebDataBinder webDataBinder){
        Object data = webDataBinder.getTarget();
        System.out.println(data);
    }
    /**
     * 全局异常处理
     */
    @ExceptionHandler({Exception.class})
    public void exceptionHandler(){
        throw new RuntimeException("全局异常处理!");
    }
}

2、创建测试Controller

/**
 * @Description:
 * @Author: Guo.Yang
 * @Date: 2022/10/10/17:48
 */
@RestController
public class HelloController {
    /**
     * 测试controller参数校验
     * @param userDto
     * @return
     */
    @RequestMapping("/test/handler")
    public String testHandler(@Validated @RequestBody UserDto userDto){
        // 测试全局异常处理
//        System.out.println(1/0);
        System.out.println(userDto);
        return "test handler";
    }
    /**
     * 测试get请求,是否会进入 @InitBinder 参数初始化
     * --> 表现是不会的
     * @param id
     * @return
     */
    @GetMapping("/test/{id}")
    public String testHandler(@PathVariable int id){
        System.out.println(id);
        return "test handler";
    }
}

3、示例

package cn.hsa.pss.pw.pcs.manage.exception;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.hsaf.core.framework.web.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
/**
 * @Description: 全局异常处理
 * @Author: Guo.Yang
 * @Date: 2023/08/09/10:19
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 基础异常
     */
    @ExceptionHandler(AppException.class)
    public WrapperResponse<String> baseException(AppException e) {
        return WrapperResponse.error(e.getCode(),e.getMessage(), null);
    }
    /**
     * 业务异常
     */
    @ExceptionHandler(RuntimeException.class)
    public WrapperResponse<String> runtimeException(RuntimeException e) {
        log.error("接口出现异常",e);
        return WrapperResponse.error(-1, e.getMessage(), null);
    }
    @ExceptionHandler(NoHandlerFoundException.class)
    public WrapperResponse handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return WrapperResponse.error(HttpStatus.NOT_FOUND.value(), "路径不存在,请检查路径是否正确", null);
    }
    @ExceptionHandler(AccessDeniedException.class)
    public WrapperResponse handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage());
        return WrapperResponse.error(HttpStatus.FORBIDDEN.value(), "没有权限,请联系管理员授权", null);
    }
    @ExceptionHandler(AccountExpiredException.class)
    public WrapperResponse handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return WrapperResponse.fail(e.getMessage(), null);
    }
    @ExceptionHandler(Exception.class)
    public WrapperResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        return WrapperResponse.fail(e.getMessage(), null);
    }
    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return WrapperResponse.fail(message, null);
    }
}
相关文章
|
机器学习/深度学习 存储 数据可视化
Langchain的一些问题和替代选择
Langchain因其简化大型语言模型(llm)的交互方面的到关注。凭借其高级的API可以简化将llm集成到各种应用程序中的过程。
1219 1
|
网络协议 编译器 C语言
Visual Studio 2022 中解决使用scanf报错的方法(一劳永逸)
宝子们好呀!在上一篇文章中教大家任何安装完成Visual Studio 2022,还没有安装的朋友们可以到这里来看一下呀:Visual Studio 2022下载安装教程 安装完成后,很多新手小白在使用Visual Studio 2022编译器的过程中使用到scanf后会出现报错的情况,也不知道如果改正,所以今天我就来给大家分享解决这个问题的办法。
892 0
|
机器学习/深度学习 编解码 并行计算
论文阅读笔记 | Transformer系列——CSWin Transformer
论文阅读笔记 | Transformer系列——CSWin Transformer
1104 0
论文阅读笔记 | Transformer系列——CSWin Transformer
|
缓存 应用服务中间件 nginx
Web服务器的缓存机制与内容分发网络(CDN)
【8月更文第28天】随着互联网应用的发展,用户对网站响应速度的要求越来越高。为了提升用户体验,Web服务器通常会采用多种技术手段来优化页面加载速度,其中最重要的两种技术就是缓存机制和内容分发网络(CDN)。本文将深入探讨这两种技术的工作原理及其实现方法,并通过具体的代码示例加以说明。
1037 1
stm32f407探索者开发板(八)——按键输入实验--GPIO做输入
stm32f407探索者开发板(八)——按键输入实验--GPIO做输入
257 0
|
存储 SQL
SQL Server 存储过程 触发器 事务处理
SQL Server 存储过程 触发器 事务处理
283 0
|
数据可视化 Java
《IntelliJ IDEA 插件开发》第二节:开发摸鱼看书的侧边栏窗体
一、说明 二、需求目的 三、案例开发 1. 工程结构 2. 创建 UI 窗体 3. ToolWindow 工具框 4. Configurable 配置框 5. 配置 plugin.xml 四、插件测试 五、总结 六、系列推荐
1415 0
《IntelliJ IDEA 插件开发》第二节:开发摸鱼看书的侧边栏窗体
|
安全 Linux 数据安全/隐私保护
Centos虚拟机安装配置与MobaXterm工具及Linux常用命令(上)
Centos虚拟机安装配置与MobaXterm工具及Linux常用命令(上)
419 1
|
关系型数据库 MySQL
MySQL中TIMESTAMPDIFF和TIMESTAMPADD函数的用法
MySQL中TIMESTAMPDIFF和TIMESTAMPADD函数的用法
717 0