Spring 有更简单的异常处理技术吗? [英] Is there a simpler exception handling technique for Spring?
问题描述
我已经阅读了有关使用 @ExceptionHandler 的基于控制器的异常的信息.
I have read about controller based exceptions using @ExceptionHandler.
我已阅读有关使用 @ControllerAdvice 进行全局异常处理的文章.
I have read about global exception handling using @ControllerAdvice.
我还阅读了有关扩展 HandlerExceptionResolver 以进行更深入的异常处理的文章.
I have also read about extending HandlerExceptionResolver for more in-depth exception handling.
然而,我最理想的做法是能够在我的应用程序的任何层抛出一个全局异常,其中包含指示返回给客户端的 JSON 响应的参数.
However, what I would ideally like to do is be able to throw a global exception with parameters that dictate a JSON response returned to the client, at any layer in my application.
例如:
throw new CustomGlobalException(HttpStatus.UNAUTHORISED, "This JWT Token is not Authorised.")
throw new CustomGlobalException(HttpStatus.FORBIDDEN, "This JWT Token is not valid.")
这将根据我创建的模型以及状态返回一个 JSON 响应,例如:
This would then return a JSON response based on the model I've created, along with the status, such as :
{
"success" : "false",
"message" : "This JWT Token is not Authorised."
}
为了将其作为 REST 响应从我的控制器返回.这样的事情可能吗?或者我是否必须按照文档中的描述对所有内容进行自定义错误异常处理.
And for this to be returned as a REST response from my controller. Is something like this possible? Or Do I have to go through the process of making custom error exceptions for everything as described in the documentation.
为了澄清,我要求异常中断正在进行的任何进程,可能是从数据库中获取数据,并立即将给定的异常返回给客户端.我有一个 web mvc 设置.
To clarify, I require the exception to interrupt whatever the ongoing process is, perhaps fetching data from the database, and immediately return the given exception to the client. I have a web mvc setup.
更多详情:
@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);
}
推荐答案
按照我关于如何处理异常的帖子 此处,您可以编写自己的处理程序,
Following my post on how to handle exception here, you can write your own handler something like this,
class CustomGlobalException {
String message;
HttpStatus status;
}
@ExceptionHandler(CustomGlobalException.class)
public ResponseEntity<Object> handleCustomException(CustomGlobalException ex,
WebRequest request) {
Map<String, Object> response = new HashMap<>();
response.put("success", "false");
response.put("message", ex.getMessage());
return new ResponseEntity<>(response, ex.getStatus());
}
上面提到的代码将处理CustomGlobalException发生的任何代码层.
Code mentioned above will handle CustomGlobalException occurred any layer of code.
这篇关于Spring 有更简单的异常处理技术吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!