Jas*_*ues 7 java spring spring-mvc kotlin spring-boot
我设置了以下控制器建议,以返回错误条件的API合同:
@ControllerAdvice
public class ExceptionHandler : ResponseEntityExceptionHandler()
{
@ExceptionHandler(Throwable::class)
@ResponseBody
public fun onException(ex: Throwable): ResponseEntity<ErrorResponse>
{
val errorResponse = ErrorResponse(
response = ResponseHeader(ex.responseCode(), ex.message))
return ResponseEntity(errorResponse, HttpStatus.UNAUTHORIZED);
}
}
Run Code Online (Sandbox Code Playgroud)
这是工作的罚款,然后停止工作.现在所有异常都被路由到BasicErrorController,返回以下格式:
{
"timestamp" : 1450495303166,
"status" : 403,
"error" : "Forbidden",
"message" : "Access Denied",
"path" : "/profile/candidates"
}
Run Code Online (Sandbox Code Playgroud)
以上是一个很好的自以为是的起点,但现在它不会让步.
ExceptionHandlerExceptionResolver但是没有用的实例替换错误处理程序.HttpServletRequest重新路由到自定义错误控制器时,原始异常不再存在.需要此信息才能向客户端返回适当的响应.我怎么样:
在启动弹簧日志:
main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in exceptionHandler
main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in responseEntityExceptionHandler
Run Code Online (Sandbox Code Playgroud)
编辑:
在阅读了Spring Boot文档之后,我现在认为BasicErrorController只应该针对任何未被a处理的异常触发@ControllerAdvice.这似乎没有发生.所以问题是为什么?
我还有一个 Spring Security 过滤器,用于评估 API-Key 和 Access-Token 标头凭据。@ControllerAdvice 在这里不起作用 - 很公平,因为我们不处理控制器端点!
使用 EntryPoint 和 AcessDeniedHandler 处理来自安全过滤器的异常。里面可以配置的有:
.exceptionHandling()
Run Code Online (Sandbox Code Playgroud)
如果您在过滤器中扩展 AbstractAuthenticationProcessingFilter,请配置 FailureHandler。
setAuthenticationFailureHandler()
Run Code Online (Sandbox Code Playgroud)
如果您将应用程序部署在应用程序服务器下,那么 ErrorController 将被覆盖。
| 归档时间: |
|
| 查看次数: |
3950 次 |
| 最近记录: |