Spring Zuul中如何在ErrorController中打印异常
在Spring Boot的ErrorController中打印异常日志
嘿,这个问题我之前做Spring Boot项目时也碰到过!要在你的ErrorController里打印触发错误的异常,Spring Boot其实已经提供了很顺手的工具类——ErrorAttributes,这是最规范的实现方式,比直接从请求里捞信息靠谱多了。
实现步骤
- 注入
ErrorAttributes:这个是Spring容器管理的核心bean,专门封装错误请求的所有信息,包括异常对象、状态码、请求路径等。 - 获取当前请求的错误信息:通过
RequestContextHolder拿到当前请求的属性,再用ErrorAttributes提取异常详情。 - 用SLF4J打印日志:Spring推荐用SLF4J作为日志门面,配合logback这类实现输出日志,这也是项目里的常规做法。
修改后的完整代码
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; @RestController public class ErrorHandlerController implements ErrorController { // 初始化SLF4J日志实例 private static final Logger logger = LoggerFactory.getLogger(ErrorHandlerController.class); @Autowired private ErrorAttributes errorAttributes; @Override public String getErrorPath() { return "/error"; } @RequestMapping("/error") public String error() { // 获取当前请求的属性对象 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // 提取错误详情:第二个参数true表示包含完整的异常栈信息 Map<String, Object> errorDetails = errorAttributes.getErrorAttributes(requestAttributes, true); // 获取触发错误的异常对象 Throwable exception = errorAttributes.getError(requestAttributes); // 打印日志:如果有异常对象,就打印带栈信息的错误;否则打印错误详情 if (exception != null) { logger.error("系统发生异常: 错误信息={}, 请求路径={}", errorDetails.get("message"), errorDetails.get("path"), exception); } else { logger.error("系统发生未知错误: {}", errorDetails); } // 返回自定义的错误响应(也可以改成返回JSON格式,比如用ResponseEntity) return "服务器内部错误,请稍后重试"; } }
补充:另一种直接从请求获取的方式
如果你不想用ErrorAttributes,也可以通过HttpServletRequest直接获取Servlet规范定义的错误属性,不过这种方式不够优雅,兼容性也稍差:
@RequestMapping("/error") public String error(HttpServletRequest request) { Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception"); if (exception != null) { logger.error("系统异常", exception); } return "服务器内部错误"; }
注意事项
- 确保项目已经引入了SLF4J的日志实现(比如logback),Spring Boot默认已经集成,一般不需要额外配置。
errorAttributes.getErrorAttributes的第二个参数设为true时,会包含完整的异常栈信息,方便排查问题;设为false则只返回基本错误信息。
内容的提问来源于stack exchange,提问作者Tiina
相关产品推荐
相关产品推荐

