【转载】Springboot2.3.5实现全局异常处理

参考

环境

  • Springboot 2.3.5
  • slf4j (自带)

步骤

  1. 在 exception/ 创建全局异常处理类 GlobalExceptionHandler.java

/**
 * @Author 夏秋初
 * @Date 2021/8/6 23:04
 * @ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
 * @ControllerAdvice 可以指定扫描范围
 */
@ControllerAdvice(basePackages = "com.xxx.suddenlynlinelearningplatform.controller")
public class GlobalExceptionHandler {

    /**
     * 日志类
     */
    public static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 获取请求信息
     */
    @Autowired
    HttpServletRequest httpServletRequest;

    /**
     * @ExceptionHandler 表示拦截异常
     */

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<ResponseBodyUtils<Map<String, String>>> errorResult(RuntimeException e)  {
        // 通过判断异常是否属于自定义的异常类,进行相应的处理
//        if(e instanceof JwtAuthException){
//            System.out.println("权限拦截器异常");
//        }
        /**
         * 错误类名
         * e.getClass().getName();
         * 错误内容
         * e.getMessage();
         */
        //
        String errorCode = UUID.randomUUID().toString();
        // 记录日志
        LOGGER.error(
                "\r\nERROR_CODE:"+
                errorCode+
                "\r\nURL:"+
                httpServletRequest.getRequestURI()+
                "\r\nMETHOD:"+
                httpServletRequest.getMethod()+
                "\r\nPARAMETERS:"+
                httpServletRequest.getQueryString()+
                "\r\nERRPR_TYPE:"+
                e.getClass().getName()+
                "\r\n ERROR_MESSAGE:"+e.getMessage());
        //
        Map<String, String> map = new HashMap<String, String>(){{
            put("error_code", errorCode);
        }};
        //
        System.out.println("拦截到异常:"+e.getClass().getName());
        System.out.println("异常内容:"+e.getClass());
        //
        return ResponseEntity.status(500).body(new ResponseBodyUtils<Map<String, String>>(map));
    }
}


  1. exception / 创建自定义异常类 JwtAuthException
public class JwtAuthException extends  RuntimeException{
    private static final long serialVersionUID  = 1L;
    private Integer httpCode                    = 200;
    // 可以判断是自定义异常的时候获取对应的属性,来优化响应内容
    private String  responseMessage             = "权限验证失败";
}
  1. 在控制器内编写报错

@Api(tags = "测试类", value = "测试类")
@RestController
@RequestMapping("/test")
public class Test {
    @Autowired
    StudentService studentService;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ResponseBodyUtils<Student> index() throws  JwtAuthException{
        throw new JwtAuthException();
//        return  new ResponseBodyUtils( studentService.findById(18));
    }
}

  1. 测试结果

image

posted @   夏秋初  阅读(86)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示