首页 > 解决方案 > 如何映射和记录异常但仍然让 SpringBoot 呈现 JSON 响应?

问题描述

我想要一个全局异常处理程序

a) 将某些异常映射到 HTTP 响应代码,可能通过将例如转换NoSuchElementExceptionResponseStatusException

b) 根据异常添加日志记录,例如 NullPointerException 比 NoSuchElementExceptions 获得更详细的日志记录

c) 使用 SpringBoot JSON 错误响应,即{ timestamp: ..., status: ..., error: ... }

我读

但大多数方法,比如@ExceptionHandler希望我提供 HTTP 响应正文。我想使用原始的 SpringBoot JSON 错误消息,尽管它可能是由DefaultErrorAttributes类制作的。

有任何想法吗?

标签: spring-bootexception

解决方案


我终于发现显而易见的解决方案@ExceptionHandler确实有效,但我必须添加server.error.message: always以将异常消息也添加到响应中!(默认是可以的,因为它可以包含敏感信息!)

除此之外,它看起来像:

@RestControllerAdvice
class ExceptionHandlers {

   @ExceptionHandler
   fun handleAllErrors(e: Throwable, response: HttpServletResponse) {
      ...
      response.sendError(status, message)
   }
}

推荐阅读