You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot自定义/error路由仍出白标错误(状态码999)求助

问题排查与解决方案

核心原因

Spring Boot默认通过ErrorMvcAutoConfiguration提供了BasicErrorController,它会优先处理/error路径的请求,导致你自定义的控制器无法生效。状态码999是默认错误处理逻辑未匹配到具体状态时返回的标识。

修复方案

方案1:实现ErrorController接口接管错误处理

直接实现Spring Boot的ErrorController接口,覆盖默认的错误处理逻辑:

import javax.servlet.RequestDispatcher
import javax.servlet.http.HttpServletRequest
import org.springframework.boot.web.servlet.error.ErrorController
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class CustomErrorController : ErrorController {

    @GetMapping("/error")
    fun handleError(request: HttpServletRequest): String {
        // 获取原始请求的状态码
        val statusCode = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) as Int?
        return "Custom error page - Status code: ${statusCode ?: 500}"
    }

    override fun getErrorPath(): String {
        return "/error"
    }
}

方案2:使用@ControllerAdvice全局异常处理

如果需要更灵活地处理不同类型的异常或错误场景,推荐使用全局异常处理器:

import javax.servlet.RequestDispatcher
import javax.servlet.http.HttpServletRequest
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody

@ControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(Exception::class)
    @ResponseBody
    fun handleAllExceptions(ex: Exception, request: HttpServletRequest): String {
        val statusCode = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) as Int?
        return "Custom error message: ${ex.message ?: "Unknown error"} - Status code: ${statusCode ?: 500}"
    }
}

额外检查点

  • 确保项目引入了spring-boot-starter-web依赖,没有该依赖Spring MVC的控制器逻辑无法生效。
  • 主应用类的@SpringBootApplication注解默认会扫描同级及子目录的组件,你的控制器放在同级目录没问题,但若有自定义@ComponentScan范围需确认包含该类。
  • 方法名尽量遵循小驼峰规范(如showError而非ShowError),虽然Kotlin允许大写开头,但符合规范能避免潜在的映射问题。

内容的提问来源于stack exchange,提问作者Jatin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:31:24