news 2026/7/7 14:55:58

SpringBoot 全局异常处理与日志记录——统一规范实战

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringBoot 全局异常处理与日志记录——统一规范实战

线上系统出问题不可怕,可怕的是出了问题找不到原因。统一的异常处理和规范的日志记录是任何生产系统必备的基础设施。

一、全局异常处理

1. 自定义业务异常

publicclassBusinessExceptionextendsRuntimeException{privateintcode;privateStringmessage;publicBusinessException(intcode,Stringmessage){super(message);this.code=code;this.message=message;}// 常用错误码publicstaticBusinessExceptionnotFound(Stringmsg){returnnewBusinessException(404,msg);}publicstaticBusinessExceptionbadRequest(Stringmsg){returnnewBusinessException(400,msg);}publicstaticBusinessExceptionunauthorized(Stringmsg){returnnewBusinessException(401,msg);}publicstaticBusinessExceptionforbidden(Stringmsg){returnnewBusinessException(403,msg);}}

2. 全局异常处理器

@RestControllerAdvicepublicclassGlobalExceptionHandler{privatestaticfinalLoggerlog=LoggerFactory.getLogger(GlobalExceptionHandler.class);@ExceptionHandler(BusinessException.class)publicResultVO<?>handleBusiness(BusinessExceptione){log.warn("业务异常: code={}, msg={}",e.getCode(),e.getMessage());returnResultVO.error(e.getCode(),e.getMessage());}@ExceptionHandler(MethodArgumentNotValidException.class)publicResultVO<?>handleValidation(MethodArgumentNotValidExceptione){Stringmsg=e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(";"));returnResultVO.error(400,msg);}@ExceptionHandler(ConstraintViolationException.class)publicResultVO<?>handleConstraint(ConstraintViolationExceptione){Stringmsg=e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));returnResultVO.error(400,msg);}@ExceptionHandler(NoHandlerFoundException.class)publicResultVO<?>handle404(NoHandlerFoundExceptione){returnResultVO.error(404,"接口不存在: "+e.getRequestURL());}@ExceptionHandler(Exception.class)publicResultVO<?>handleOther(Exceptione){log.error("系统异常",e);returnResultVO.error(500,"服务器繁忙,请稍后重试");}}

二、统一日志记录

1. 请求日志拦截器

@ComponentpublicclassLogInterceptorimplementsHandlerInterceptor{privatestaticfinalLoggerlog=LoggerFactory.getLogger(LogInterceptor.class);@OverridepublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler){// 记录请求开始时间request.setAttribute("startTime",System.currentTimeMillis());returntrue;}@OverridepublicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex){longstart=(long)request.getAttribute("startTime");longduration=System.currentTimeMillis()-start;log.info("[{}] {} {} → {} ({}ms)",request.getMethod(),request.getRequestURI(),request.getQueryString()!=null?"?"+request.getQueryString():"",response.getStatus(),duration);}}

2. 注册拦截器

@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@AutowiredprivateLogInterceptorlogInterceptor;@OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(logInterceptor).addPathPatterns("/api/**");}}

3. 日志级别配置

logging:level:root:INFOcom.zhang:DEBUGcom.zhang.seckill.mapper:TRACEfile:path:/var/log/appname:${logging.file.path}/app.loglogback:rolling policy:max-history:30max-file-size:100MB

三、日志最佳实践

// ✅ 正确:带参数占位符log.info("用户 {} 创建订单 {}",userId,orderNo);// ❌ 错误:字符串拼接log.info("用户 "+userId+" 创建订单 "+orderNo);// ✅ 正确:包含上下文信息log.warn("支付失败: orderNo={}, amount={}, error={}",orderNo,amount,error);// ❌ 错误:没信息量的日志log.info("支付失败");

💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!每周更新 Java/Python/爬虫 实战干货,不让你白来。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/7 14:53:49

B站视频下载神器:解锁大会员4K高清与充电专属内容的智能方案

B站视频下载神器&#xff1a;解锁大会员4K高清与充电专属内容的智能方案 【免费下载链接】bilibili-downloader B站视频下载&#xff0c;支持下载大会员清晰度4K&#xff0c;持续更新中 项目地址: https://gitcode.com/gh_mirrors/bil/bilibili-downloader 你是否曾经遇…

作者头像 李华
网站建设 2026/7/7 14:47:32

高精度数据采集系统硬件选型与设计实践

1. MCP3428与MKV46F256VLH16的硬件选型解析在工业级数据采集系统中&#xff0c;ADC&#xff08;模数转换器&#xff09;和微控制器的选型直接决定了整个系统的精度上限和实时性表现。MCP3428作为Microchip推出的18位Δ-Σ型ADC芯片&#xff0c;其核心优势在于集成了可编程增益放…

作者头像 李华
网站建设 2026/7/7 14:46:11

allure的安装及配置

allure是一款轻量级并且非常灵活的开源 测试报告框架。 它支持绝大多数测试框架&#xff0c;它简单易用&#xff0c;易于集成。 一、allure的下载 -下载网址&#xff08;allure官网&#xff09;&#xff1a;Allure Report — Open-source HTML test automation report tool …

作者头像 李华
网站建设 2026/7/7 14:42:23

智能抖音无水印下载工具:一站式解决视频保存难题

智能抖音无水印下载工具&#xff1a;一站式解决视频保存难题 【免费下载链接】douyin-downloader A practical Douyin downloader for both single-item and profile batch downloads, with progress display, retries, SQLite deduplication, and browser fallback support. 抖…

作者头像 李华
网站建设 2026/7/7 14:39:15

九大网盘直链下载助手终极指南:告别限速的简单解决方案

九大网盘直链下载助手终极指南&#xff1a;告别限速的简单解决方案 【免费下载链接】Online-disk-direct-link-download-assistant 一个基于 JavaScript 的网盘文件下载地址获取工具。基于【网盘直链下载助手】修改 &#xff0c;支持 百度网盘 / 阿里云盘 / 中国移动云盘 / 天翼…

作者头像 李华