@ExceptionHandler没有被触发?

时间:2018-06-25 08:51:40

标签: spring spring-mvc spring-boot spring-security spring-data

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

当引发异常时,我的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());
}
}

CustomException.class:

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);
}
}

我在Web配置中具有所有必需的属性:

<!--<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>

花了一段时间解决这个问题。

这就是我得到的:

enter image description here

1 个答案:

答案 0 :(得分:2)

您的异常不会被@ControllerAdvice捕获,因为您是从带有@Component而不是@Controller注释的类中抛出异常的。

根据文档:

  

@Component的声明类的专业化   @ ExceptionHandler,@ InitBinder或@ModelAttribute方法   在多个@Controller类之间共享。

您可以找到更完整的参考文献here