当数据库连接失败( Spring Security抛出InternalAuthenticationServiceException )时,我的Spring Boot OAuth REST应用程序返回“401Authorized”状态。这很奇怪,我需要将状态更改为"500内部服务器错误“,以便客户端可以提供一些适当的描述,如”服务不可用“。
如果我使用WebResponseExceptionTranslator,那么我可以捕获响应,但是如果我改变HTTP状态,它只在数据库激活时才起作用。如果数据库被关闭,那么我会再次得到"401 Unauthorized“。
我如何才能最优雅地解决这个问题?
发布于 2017-10-26 20:44:54
根据抛出异常的级别,您可能希望将异常处理程序添加到登录控制器:
@ExceptionHandler(InternalAuthenticationServiceException.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
// convert exception to 500, add logging and
}在这里了解有关异常处理的更多信息:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
发布于 2017-10-27 00:16:46
我通过在自定义UserDetailService中的jdbcTemplate请求周围添加"try catch“来解决这个问题。
protected List<UserDetails> loadUsersByUsername(String username) {
try {
userDetailsList = this.getJdbcTemplate().query( USERS_BY_USERNAME, new String[]{username},
new RowMapper() {
public UserDetails mapRow( ResultSet rs, int rowNum ) throws SQLException {
String username = rs.getString( 1 );
/* etc. map user fields */
return new SecurityUser( username, /* other params... */ );
}
});
} catch (CannotGetJdbcConnectionException e){
logger.error( "UserDetailService SQL error: " + e.getMessage(), e );
}
return userDetailsList;
}然后我通过WebResponseExceptionTranslator检查InternalAuthenticationServiceException并更改响应状态。
似乎当我抓到CannotGetJdbcConnectionException的时候,链上就会有东西被毁掉。它是有效的,但我会留下我的问题,也许有人可以提供一个更明确的解决方案。
https://stackoverflow.com/questions/46954581
复制相似问题