我正在使用 Zalando 的問題庫,并且正在運行以下問題(雙關語):
對于普通控制器拋出的問題,一切正常。在這種情況下,我有一個自定義的 Spring 過濾器。如果我從過濾器中拋出問題,回應是 500 錯誤(使用標準彈簧錯誤頁面顯示),而不是問題中指示的 400 錯誤。換句話說,例外像普通例外一樣被拋出,而不是被正確序列化為 JSON 回應。
如何確保過濾器引發的問題也得到正確處理/序列化?
我的代碼:
@Component
class UserVerifiedFilter : OncePerRequestFilter() {
@Throws(ServletException::class, IOException::class)
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
// ...
throw Problem.builder()
.withType(URI.create("https://example.org/email-unverified"))
.withTitle("Email unverified")
.withStatus(Status.BAD_REQUEST)
.withDetail("Email needs to verified to use this endpoint")
.build()
}
}
@RestControllerAdvice
class ControllerExceptionHandler : ProblemHandling, SecurityAdviceTrait
uj5u.com熱心網友回復:
設法通過添加另一個過濾器來解決這個問題,作為鏈中的第一個過濾器。
此過濾器捕獲任何例外并將其手動傳播到配置的例外處理程式。
@Component
class FilterExceptionHandler : OncePerRequestFilter() {
@Autowired
private lateinit var resolver: HandlerExceptionResolver
private val logger = LoggerFactory.getLogger(javaClass)
@Throws(ServletException::class, IOException::class)
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
try {
filterChain.doFilter(request, response)
} catch (exception: Exception) {
logger.error("Spring Security filter chain exception : {}", exception)
resolver.resolveException(request, response, null, exception)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489157.html
上一篇:錯誤GlobalExceptionHandler,錯誤401不顯示錯誤詳細資訊
下一篇:將值傳遞到例外字串訊息中