java.lang.reflect.UndeclaredThrowableException的解决

[转] https://www.jianshu.com/p/7edab536e4b9

前言

这2天开始写web接口,由于项目后端就我一个人,写起来比较慢。,遇到好多奇怪的问题,也基本只能一个人去解决。今天下午给这个问题坑了半天。现在脑壳子还疼。

问题

业务上需要实现一个功能,拦截请求的参数。检查是否包含token。项目是基于springmvc来实现的,这里很自然使用 spring 切面技术。拦截所有controller的请求,然后检查是否携带了token参数。如果没携带,则抛一个自定义异常。再调用 统一异常处理类来处理。
涉及的类如下:

package com.insigmaunited.lightai.base;

import com.insigmaunited.lightai.exception.TokenEmptyException;
import com.insigmaunited.lightai.result.Response;
import com.insigmaunited.lightai.util.StringUtil;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限拦截AOP
 * @author Administrator
 *
 */
@Component
@Aspect
public class PermissionAop {

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

    // 定义切点Pointcut
    @Pointcut("execution(* com.insigmaunited.lightai.controller.*Controller.*(..))")
    public void pointCut(){}

    @Before("pointCut()")
    public void before() throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        System.out.println(url);
        System.out.println(method);
        System.out.println(uri);
        System.out.println(queryString);

        if (StringUtil.isNotEmpty(queryString) && queryString.indexOf("token") != -1 ){
        }else{
            throw new TokenEmptyException("token缺失");
        }
    }


}

自定义异常类

package com.insigmaunited.lightai.exception;

public class TokenEmptyException extends Exception {
    public TokenEmptyException(String message) {
        super(message);
    }
}

异常统一处理类

package com.insigmaunited.lightai.exception;

import com.insigmaunited.lightai.base.BaseException;
import com.insigmaunited.lightai.result.Response;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.insigmaunited.lightai.exception.TokenEmptyException;

import javax.xml.bind.ValidationException;

@ControllerAdvice
@ResponseBody
public class ExceptionAdvice extends BaseException {

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public Response handleValidationException(ValidationException e) {
        logger.error("参数验证失败", e);
        return new Response().failure("validation_exception");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法", e);
        return new Response().failure("request_method_not_supported");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Response handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型", e);
        return new Response().failure("content_type_not_supported");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(TokenEmptyException.class)
    public Response handleTokenEmptyException(Exception e) {
        logger.error("token参数缺少", e);
        return new Response().failure("token参数缺少");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        logger.error("服务运行异常", e);
        return new Response().failure("服务运行异常");
    }
}

此时调用接口,期望返回的是应该

{
    "success": false,
    "message": "token参数缺少",
    "data": null
}

实际返回的是

{
    "success": false,
    "message": "服务运行异常",
    "data": null
}

控制台的错误如下:

http://localhost:8080/user/3/profile
GET
/user/3/profile
null
[ ERROR ] 2017-12-08 18:29:19 - com.insigmaunited.lightai.exception.ExceptionAdvice - ExceptionAdvice.java(63) - 服务运行异常
java.lang.reflect.UndeclaredThrowableException
    at com.insigmaunited.lightai.controller.UserController$$EnhancerBySpringCGLIB$$e4eb8ece.profile(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
    at org.apache.tomcat.util.net.Nio2Endpoint$SocketProcessor.doRun(Nio2Endpoint.java:1688)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.net.AbstractEndpoint.processSocket(AbstractEndpoint.java:914)
    at org.apache.tomcat.util.net.Nio2Endpoint$Nio2SocketWrapper$4.completed(Nio2Endpoint.java:536)
    at org.apache.tomcat.util.net.Nio2Endpoint$Nio2SocketWrapper$4.completed(Nio2Endpoint.java:514)
    at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126)
    at sun.nio.ch.Invoker$2.run(Invoker.java:218)
    at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.insigmaunited.lightai.exception.TokenEmptyException: token缺失
    at com.insigmaunited.lightai.base.PermissionAop.before(PermissionAop.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:620)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:602)
    at org.springframework.aop.aspectj.AspectJMethodBeforeAdvice.before(AspectJMethodBeforeAdvice.java:41)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    ... 45 more

这很奇怪了。为何我抛的自定义异常变成了 UndeclaredThrowableException,导致不能被统一异常处理器正常处理。

原因

通过搜索引擎,最终找到的原因:

我们的异常处理类,实际是 动态代理的一个实现。

如果一个异常是检查型异常并且没有在动态代理的接口处声明,那么它将会被包装成UndeclaredThrowableException.
而我们定义的自定义异常,被定义成了检查型异常,导致被包装成了UndeclaredThrowableException

官方的文档解释

异常的区分

解决

知道原因就很简单了。要么 抛 java.lang.RuntimeException or java.lang.Error 非检查性异常, 要么接口要声明异常。

这里选择 修改 自定义异常为 运行时异常即可。

package com.insigmaunited.lightai.exception;

public class TokenEmptyException extends RuntimeException {
    public TokenEmptyException(String message) {
        super(message);
    }
}

教训

1、自定义异常尽可能定义成 运行时异常。
2、对异常的概念不清晰。基础不扎实。

 
 
10人点赞
 
 


作者:有时右逝
链接:https://www.jianshu.com/p/7edab536e4b9
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2022-05-25 17:14  小小鸟儿!  阅读(5092)  评论(0编辑  收藏  举报