Spring是否有更简单的异常处理技术? [英] Is there a simpler exception handling technique for Spring?

查看:74
本文介绍了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.")

然后,这将基于我创建的模型以及状态(例如:

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 .

这篇关于Spring是否有更简单的异常处理技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆