java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot 异常处理

Spring Boot 中的默认异常处理机制解析(如 /error 接口)

作者:南姜先生

SpringBoot通过/error接口默认处理异常,使用BasicErrorController返回结构化JSON或HTML错误页面,支持自定义ErrorAttributes、ControllerAdvice及错误模板,配置项可调整错误路径和格式,本文给大家介绍Spring Boot 中的默认异常处理机制解析,感兴趣的朋友一起看看吧

Spring Boot 中,为了简化 Web 应用的异常处理流程,它提供了一套默认的全局异常处理机制,其中最核心的就是 /error 接口。这个接口是 Spring Boot 提供的一个内置错误页面控制器(BasicErrorController),用于统一返回错误信息。

🧠 一句话总结:

✅ Spring Boot 默认使用 BasicErrorController 来处理所有未被捕获的异常,并通过 /error 接口返回结构化的错误响应或跳转到错误页面(如 HTML 页面)。

🔍 一、默认行为概览

请求类型返回内容
浏览器请求(HTML)跳转到 /error 页面(如 error.html
API 请求(JSON/REST)返回 JSON 格式的错误信息

例如:

🛠️ 二、核心组件解析

1. BasicErrorController

这是 Spring Boot 默认提供的错误处理器,负责处理 /error 请求。

@Controller
@RequestMapping("${server.error.path:${spring.mvc.async.request-timeout}}")
public class BasicErrorController extends AbstractErrorController {
    ...
}

2. ErrorAttributes 接口

该接口定义了错误信息的内容来源,包括:

默认实现是 DefaultErrorAttributes,你也可以自定义。

3. ErrorViewResolver 接口

用于解析 HTML 错误页面。例如:

Spring Boot 会根据状态码优先匹配具体页面。

📦 三、默认返回的 JSON 错误结构

当你访问一个 REST 接口时,如果发生异常且没有被 @ExceptionHandler@ControllerAdvice 捕获,Spring Boot 会返回如下格式的 JSON 响应:

{
  "timestamp": "2025-07-12T10:45:00.000+00:00",
  "status": 404,
  "error": "Not Found",
  "path": "/not-found"
}

字段说明:

字段名含义
timestamp错误发生时间
statusHTTP 状态码
error错误描述
exception异常类名(仅当 spring.boot.debug=true 时显示)
message异常消息(可选)
path出错的请求路径

🌐 四、如何自定义错误处理?

虽然 Spring Boot 提供了默认的错误处理机制,但在实际项目中我们通常需要进行定制:

1. 方式一:自定义 ErrorAttributes

你可以实现 ErrorAttributes 接口来自定义错误信息内容:

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorMap = super.getErrorAttributes(webRequest, options);
        errorMap.put("customInfo", "This is a custom error info.");
        return errorMap;
    }
}

2. 方式二:继承 BasicErrorController 自定义控制器

@RestController
@RequestMapping("${server.error.path:/error}")
public class CustomErrorController extends BasicErrorController {
    public CustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes, new ErrorProperties());
    }
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(new ServletWebRequest(request), true);
        return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

3. 方式三:创建自定义错误页面(HTML)

将 HTML 页面放在以下位置之一即可:

Spring Boot 会根据 HTTP 状态码自动选择对应的页面。

4. 方式四:使用 @ControllerAdvice 全局处理异常

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception ex, HttpServletRequest request) {
        Map<String, Object> errorBody = new HashMap<>();
        errorBody.put("error", ex.getMessage());
        errorBody.put("path", request.getRequestURI());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorBody);
    }
}

这种方式比默认机制更灵活,适用于大型项目。

⚙️ 五、配置相关属性(application.yml)

你可以在 application.ymlapplication.properties 中配置一些与错误相关的参数:

spring:
  mvc:
    async:
      request-timeout: 0 # 禁用超时控制
server:
  error:
    path: /my-error     # 自定义错误路径
    whitelabel:
      enabled: false    # 关闭默认白标错误页

✅ 六、总结

项目内容
默认错误端点/error
默认控制器BasicErrorController
默认错误信息DefaultErrorAttributes
默认视图支持支持 HTML 错误页面(按状态码命名)
JSON 输出格式包含 timestamp, status, error, path 等字段
可扩展性支持自定义 ErrorAttributes、ErrorController、HTML 页面、@ControllerAdvice

到此这篇关于Spring Boot 中的默认异常处理机制(如 /error 接口)的文章就介绍到这了,更多相关Spring Boot 异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文