首页 > 解决方案 > @ExceptionHandler 没有被触发?

问题描述

我在这个主题上看到了其他重复的堆栈溢出问题,但似乎没有一个能复制我的情况。

抛出异常时,我的 ExceptionHandler 类不会将其拾取并返回 json,而是将带有异常详细信息的默认 500 代码作为 HTML 返回给客户端。我已经检查过了,Spring 确实初始化了我的 ExceptionHandler 类,但无论出于何种原因,这些方法都没有被调用。

GlobalExceptionHandler.class:

@ControllerAdvice
@RequestMapping(produces = "application/json")
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

public GlobalExceptionHandler(){
    LOG.debug("This gets called in logs...");
}

@ExceptionHandler({CustomException.class})
public @ResponseBody ResponseEntity<Object> handleCustomException(HttpServletRequest request,
                                             CustomException ex) {

    LOG.debug("This does not get called...");
    Map<String, Object> response = new HashMap<>();

    response.put("message", ex.getMessage());
    return new ResponseEntity<>(response, ex.getCode());
}
}

自定义异常类:

public class CustomException extends RuntimeException{

private HttpStatus code;
private String message;

public CustomException(final HttpStatus code, final String message){

    this.code = code;
    this.message = message;
}


/**
 * Gets message.
 *
 * @return Value of message.
 */
public String getMessage() {
    return message;
}

/**
 * Sets new code.
 *
 * @param code
 *         New value of code.
 */
public void setCode(HttpStatus code) {
    this.code = code;
}

/**
 * Sets new message.
 *
 * @param message
 *         New value of message.
 */
public void setMessage(String message) {
    this.message = message;
}

/**
 * Gets code.
 *
 * @return Value of code.
 */
public HttpStatus getCode() {
    return code;
}
}

异常处理程序在此处触发:

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

@Autowired
private JwtTokenProvider tokenProvider;

@Autowired
private CustomUserDetailsService customUserDetailsService;

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain
        filterChain) throws ServletException, IOException {

    logger.debug("Filtering request for JWT header verification");

    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("{}", new CustomException(HttpStatus.UNAUTHORIZED, "No Valid JWT Token Provided"));
        throw new CustomException(HttpStatus.UNAUTHORIZED, "No Valid JWT Token Provided");
    }

    filterChain.doFilter(request, response);
}
}

我在网络配置中有所有必要的属性:

<!--<context:annotation-config />-->
<tx:annotation-driven/>
<context:component-scan base-package="com.app.controller"/>

我的 Web.xml:

<web-app>

<!-- For web context -->
<servlet>
    <servlet-name>appDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appDispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- Logging -->
<context-param>
    <param-name>logbackConfigLocation</param-name>
    <param-value>/WEB-INF/classes/logback.xml</param-value>
</context-param>

<filter>
    <filter-name>jwtFilter</filter-name>
    <filter-class>com.app.controller.security.filters.JwtAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>jwtFilter</filter-name>
    <servlet-name>appDispatcher</servlet-name>
</filter-mapping>

</web-app>

一直在考虑这个问题。。

这就是我得到的全部:

在此处输入图像描述

标签: springspring-mvcspring-bootspring-securityspring-data

解决方案


你的异常没有被捕获,因为你是从一个用and not@ControllerAdvice注释的类中抛出它的。@Component@Controller

根据文档:

@Component 用于声明要在多个 @Controller 类之间共享的 @ExceptionHandler、@InitBinder 或 @ModelAttribute 方法的类的特化。

您可以在此处找到更完整的参考资料。


推荐阅读