【发布时间】:2018-12-03 03:31:51
【问题描述】:
我已经阅读了有关使用 @ExceptionHandler 的基于控制器的异常。
我已阅读有关使用 @ControllerAdvice 进行全局异常处理的文章。
我还阅读了有关扩展 HandlerExceptionResolver 以进行更深入的异常处理的文章。
但是,我最理想的做法是能够在我的应用程序的任何层使用指示返回给客户端的 JSON 响应的参数引发全局异常。
例如:
throw new CustomGlobalException(HttpStatus.UNAUTHORISED, "This JWT Token is not Authorised.")
throw new CustomGlobalException(HttpStatus.FORBIDDEN, "This JWT Token is not valid.")
然后,这将根据我创建的模型以及状态返回 JSON 响应,例如:
{
"success" : "false",
"message" : "This JWT Token is not Authorised."
}
为此,我的控制器将其作为 REST 响应返回。 这样的事情可能吗?或者我是否必须按照文档中的说明对所有内容进行自定义错误异常处理。
为了澄清,我要求异常中断正在进行的进程,可能从数据库中获取数据,并立即将给定的异常返回给客户端。我有一个 web mvc 设置。
更多细节:
@ControllerAdvice
@RequestMapping(produces = "application/json")
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<Object> handleCustomException(CustomException ex,
WebRequest request) {
Map<String, Object> response = new HashMap<>();
response.put("message", ex.getMessage());
return new ResponseEntity<>(response, ex.getCode());
}
}
这里抛出异常:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain
filterChain) throws ServletException, IOException {
logger.debug("Filtering request for JWT header verification");
try {
String jwt = getJwtFromRequest(request);
logger.debug("JWT Value: {}", jwt);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
String username = tokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken
(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
} else {
logger.error("No Valid JWT Token Provided");
throw new CustomException(HttpStatus.UNAUTHORIZED, "No Valid JWT Token Provided");
}
} catch (Exception ex) {
logger.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
【问题讨论】:
标签: spring spring-mvc spring-boot spring-security spring-data-jpa