@ControllerAdvice无法处理catch块中的异常

时间:2019-07-25 11:37:14

标签: java spring rest exception

我正在我的Spring(5.0)RestFul应用程序中尝试使用GlobalExceptionHandler。

这是我的控制器类:

@Controller
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public class OrderController {

@Autowired
private OrderService orderService;

private static final Logger logger = LogManager.getLogger(Thread.currentThread().getClass().getName());


@ExceptionHandler(Exception.class)
public  ResponseEntity<com.example.of.rest.acknowledgement.Acknowledgement> handleError(HttpServletRequest request, Exception e)   {
    System.out.println("excpetion :(");
    if(e!=null) {
        e.printStackTrace();
    }
    com.example.of.rest.acknowledgement.ObjectFactory ackFact = new com.example.of.rest.acknowledgement.ObjectFactory();
    com.example.of.rest.acknowledgement.Acknowledgement ackXml = ackFact.createAcknowledgement();
    ackXml.setMessage(e.getMessage());
    ackXml.setStatus(Constants.ACK_STATUS.ERROR);
    java.util.logging.Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
    return new ResponseEntity<com.example.of.rest.acknowledgement.Acknowledgement>(ackXml, HttpStatus.INTERNAL_SERVER_ERROR);
}

@PostMapping("/orders/save")
@Consumes("application/json; charset=UTF-8")
public ResponseEntity<com.example.of.rest.acknowledgement.Acknowledgement> saveOrderAuthenticateConnector(HttpServletRequest request, @RequestBody String requestJson) throws Exception {
    HttpStatus httpStatus = null;
    com.example.of.rest.acknowledgement.Acknowledgement ackXml = null;
    String message = null;
    String status = null;
    ConnectorData connectorData =  null;
    try {
        String newToken = (String) request.getAttribute("token");
        if(newToken != null) {
            connectorData = orderService.saveConnectorDatatoDB(connectorData, "Not Retrieved", requestJson, Constants.DATA_STATUS_DB.RECIEVED, null, null, null);
            connectorData = orderService.processAndSaveOrder(requestJson, connectorData);
            connectorData = orderService.saveConnectorDatatoDB(connectorData, connectorData.getChannelOrderId(), requestJson, connectorData.getDataStatus(), 
                    connectorData.getProcessStatus(), connectorData.getErrorMessage(), connectorData.getProcessError());
            ackXml = responseService.populateAcknowledgement(connectorData, status, message);
            if(Constants.ACK_STATUS.SUCCESS.equals(ackXml.getStatus())) {
                httpStatus = HttpStatus.OK;

            }else {
                httpStatus = HttpStatus.BAD_REQUEST;
            }
        }else {
            message = "We were not able to authorize the request.";
            status = Constants.ACK_STATUS.ERROR;
            httpStatus = HttpStatus.UNAUTHORIZED;
        }
    }catch(Exception ex) {
        ex.printStackTrace();
        message = ex.getMessage();
        status = Constants.ACK_STATUS.ERROR;
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        connectorData = orderService.saveConnectorDatatoDB(connectorData, connectorData.getChannelOrderId(), requestJson, connectorData.getDataStatus(), 
                connectorData.getProcessStatus(), connectorData.getErrorMessage(), connectorData.getProcessError());

    }
    if(ackXml == null) {
        ackXml = responseService.populateAcknowledgementResponse(status, message);
    }
    return new ResponseEntity<com.example.of.rest.acknowledgement.Acknowledgement>(ackXml, httpStatus);

}
}

行中的catch块中发生异常。
connectorData = orderService.saveConnectorDatatoDB(connectorData, connectorData.getChannelOrderId(), requestJson, connectorData.getDataStatus(), 
                    connectorData.getProcessStatus(), connectorData.getErrorMessage(), connectorData.getProcessError());

我还定义了一个GlobalExceptionHandler:

@ControllerAdvice(basePackages = { "com.example.of.controller" })
@EnableWebMvc
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionController extends ResponseEntityExceptionHandler{

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<com.example.of.rest.acknowledgement.Acknowledgement> handleError(HttpServletRequest request, Exception e)   {
        System.out.println("excpetion :(");
        if(e!=null) {
            e.printStackTrace();
        }
        com.example.of.rest.acknowledgement.ObjectFactory ackFact = new com.example.of.rest.acknowledgement.ObjectFactory();
        com.example.of.rest.acknowledgement.Acknowledgement ackXml = ackFact.createAcknowledgement();
        ackXml.setMessage(e.getMessage());
        ackXml.setStatus(Constants.ACK_STATUS.ERROR);
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
        return new ResponseEntity<com.example.of.rest.acknowledgement.Acknowledgement>(ackXml, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

启动服务器时,将选择Exception处理程序类: 16:46:18,926信息[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter](ServerService线程池-83)寻找@ControllerAdvice:名称空间“ dispatcher-servlet”的WebApplicationContext:启动日期[7月4日25 16:46:17 IST 2019];父级:根WebApplicationContext 16:46:18,984信息[org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver](ServerService线程池-83)在exceptionController中检测到@ExceptionHandler方法

这是我的文件夹结构: enter image description here

我已在组件扫描中添加了所有文件夹:

@ComponentScan(basePackages = {"com.example.of", "com.example.of.config"}` )

但是当我调用url时,发生异常,我得到200(确定)响应,这不是我期望的。我想得到500或其他任何错误状态。

这是控制台日志:

16:32:09,330 INFO  [stdout] (default task-2) DEBUG | 2019-07-25 16:32:09 | [default task-2] controller.OrderController (OrderController.java:101) - ERROR MESSAGE could not execute statement

16:32:09,330 ERROR [stderr] (default task-2) java.lang.NullPointerException

16:32:09,331 ERROR [stderr] (default task-2)    at com.example.of.controller.OrderController.saveOrderAuthenticateConnector(OrderController.java:109)

16:32:09,331 ERROR [stderr] (default task-2)    at com.example.of.controller.OrderController$$FastClassBySpringCGLIB$$c31ff25f.invoke(<generated>)

16:32:09,331 ERROR [stderr] (default task-2)    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

16:32:09,331 ERROR [stderr] (default task-2)    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:747)

16:32:09,331 ERROR [stderr] (default task-2)    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)

16:32:09,331 ERROR [stderr] (default task-2)    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89)

16:32:09,331 ERROR [stderr] (default task-2)    at com.example.of.aspect.UserSessionTrackerAspect.authenticateConnector(UserSessionTrackerAspect.java:135)

16:32:09,331 ERROR [stderr] (default task-2)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

16:32:09,331 ERROR [stderr] (default task-2)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

16:32:09,331 ERROR [stderr] (default task-2)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

16:32:09,331 ERROR [stderr] (default task-2)    at java.lang.reflect.Method.invoke(Method.java:498)

16:32:09,331 ERROR [stderr] (default task-2)    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:643)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:632)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)

16:32:09,332 ERROR [stderr] (default task-2)    at com.example.of.controller.OrderController$$EnhancerBySpringCGLIB$$6b6ee1db.saveOrderAuthenticateConnector(<generated>)

16:32:09,332 ERROR [stderr] (default task-2)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

16:32:09,332 ERROR [stderr] (default task-2)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

16:32:09,332 ERROR [stderr] (default task-2)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

16:32:09,332 ERROR [stderr] (default task-2)    at java.lang.reflect.Method.invoke(Method.java:498)

16:32:09,332 ERROR [stderr] (default task-2)    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)

16:32:09,333 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)

16:32:09,334 ERROR [stderr] (default task-2)    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)

16:32:09,334 ERROR [stderr] (default task-2)    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)

16:32:09,334 ERROR [stderr] (default task-2)    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.websockets.jsr.JsrWebSocketFilter.doFilter(JsrWebSocketFilter.java:130)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)

16:32:09,334 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)

16:32:09,334 ERROR [stderr] (default task-2)    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)

16:32:09,335 ERROR [stderr] (default task-2)    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)

16:32:09,336 ERROR [stderr] (default task-2)    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)

16:32:09,336 ERROR [stderr] (default task-2)    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)

16:32:09,336 ERROR [stderr] (default task-2)    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)

16:32:09,336 ERROR [stderr] (default task-2)    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

16:32:09,336 ERROR [stderr] (default task-2)    at java.lang.Thread.run(Thread.java:748)

0 个答案:

没有答案