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

Micronaut @Error无法捕获HttpStatus.INTERNAL_SERVER_ERROR问题排查

Micronaut自定义HTML错误页面不生效,返回默认JSON消息

我在实现以HTML格式展示错误页面的处理逻辑,但未生效。系统未显示自定义错误页面,反而返回默认JSON消息:{"message": "Internal Server Error"}。

控制器代码

@Controller("/mail")
class MailController {

    @View("mail")
    @Get("/")
    fun index(): Map<String, Any?> {
        val res = HashMap<String, Any?>()
        
        // throw Exception("This is a test exception")

        return res
    }
}

错误处理器代码

import io.micronaut.http.HttpStatus

@Controller("/err")
class ErrorController {
    @View("500")
    @Error(status = HttpStatus.INTERNAL_SERVER_ERROR, global = true)
    fun errorHandler(e: Exception): Map<String, Any> {
        return HashMap()
    }
}

解决方法

  • 移除错误处理器上的@Controller注解
    Micronaut的全局错误处理器不需要标注@Controller,这个注解会将其识别为普通控制器,无法拦截全局错误。修改后的错误处理器代码:

    import io.micronaut.http.HttpStatus
    import io.micronaut.http.annotation.Error
    import io.micronaut.views.View
    import java.util.HashMap
    
    class ErrorController {
        @View("500")
        @Error(status = HttpStatus.INTERNAL_SERVER_ERROR, global = true)
        fun errorHandler(e: Exception): Map<String, Any> {
            return HashMap()
        }
    }
    
  • 确认视图模板路径正确
    确保500对应的模板文件(如500.html)存放在Micronaut默认的视图目录src/main/resources/views/下,路径错误会导致无法加载自定义页面。

  • 检查请求的Accept头
    前端请求的Accept头需要包含text/html,如果仅指定application/json,Micronaut会优先返回JSON格式错误。用浏览器直接访问接口时,默认会发送包含text/html的Accept头,可用于测试。

  • 确保异常被正确抛出
    取消控制器中异常代码的注释,确保触发错误处理器的条件成立:

    @Controller("/mail")
    class MailController {
    
        @View("mail")
        @Get("/")
        fun index(): Map<String, Any?> {
            val res = HashMap<String, Any?>()
            
            throw Exception("This is a test exception")
    
            return res
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:54:59