spring-boot - 如何映射和记录异常但仍然让 SpringBoot 呈现 JSON 响应?
问题描述
我想要一个全局异常处理程序
a) 将某些异常映射到 HTTP 响应代码,可能通过将例如转换NoSuchElementException
为ResponseStatusException
b) 根据异常添加日志记录,例如 NullPointerException 比 NoSuchElementExceptions 获得更详细的日志记录
c) 使用 SpringBoot JSON 错误响应,即{ timestamp: ..., status: ..., error: ... }
我读
- https://www.baeldung.com/exception-handling-for-rest-with-spring和
- https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-exceptionhandlers
但大多数方法,比如@ExceptionHandler
希望我提供 HTTP 响应正文。我想使用原始的 SpringBoot JSON 错误消息,尽管它可能是由DefaultErrorAttributes
类制作的。
有任何想法吗?
解决方案
我终于发现显而易见的解决方案@ExceptionHandler
确实有效,但我必须添加server.error.message: always
以将异常消息也添加到响应中!(默认是可以的,因为它可以包含敏感信息!)
除此之外,它看起来像:
@RestControllerAdvice
class ExceptionHandlers {
@ExceptionHandler
fun handleAllErrors(e: Throwable, response: HttpServletResponse) {
...
response.sendError(status, message)
}
}