Java 未调用@ControllerAdvice 异常处理程序方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29698063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:27:57  来源:igfitidea点击:

@ControllerAdvice exception handler method not get called

javaspringspring-mvcexception-handlingcontroller

提问by rachana

I am working on sample demo application for Exception Handling in Spring MVC.I am trying Exception Handling With @ControllerAdvice

我正在研究 Spring MVC 中异常处理的示例演示应用程序。我正在尝试 Exception Handling With @ControllerAdvice

I followed steps as describe in thislink.

我按照链接中描述的步骤操作。

But when i run my application i get the following error

但是当我运行我的应用程序时,我收到以下错误

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException

For more details following are the classes I am working on

有关更多详细信息,以下是我正在研究的课程

ApplicationException.java

应用异常.java

public class ApplicationException extends RuntimeException{


/**
 * 
 */
private static final long serialVersionUID = -9061684361606685158L;
private ErrorStatus errorStatus;
private int msgNumber;
private Object []args;

public ApplicationException(){}

public ApplicationException(ErrorStatus errorStatus, int msgNumber,
        Object[] args) {
    this.errorStatus = errorStatus;
    this.msgNumber = msgNumber;
    this.args = args;
  }
    //getter setters
}

Controller class

控制器类

ApplicationExceptionController.java

应用异常控制器.java

 @Controller
@RequestMapping("/exception")
public class ApplicationExceptionController {

@RequestMapping(value="/error",method=RequestMethod.GET)
@ResponseBody
public void helloException() 
{
    throw new ApplicationException(ErrorStatus.NotFound,1,new Object[]{"Website"});

  //here ErrorStatus is a enum class
}  
}

And here is the GlobalExceptionHandler class

这是 GlobalExceptionHandler 类

GlobalExceptionHandler.java

全局异常处理程序

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler
public void notFount(){
    System.out.println("----------CaughtApplicationException-----------");
}
}

dispatcher-servlet.xml

调度程序-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"  
xmlns:p="http://www.springframework.org/schema/p"      
xmlns:context="http://www.springframework.org/schema/context"  
xmlns:mvc="http://www.springframework.org/schema/mvc" 

xsi:schemaLocation=
    "http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


<context:component-scan  base-package="com.test.controller,com.test.core" />
<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    <property name="prefix" value="/WEB-INF/jsp/" />  
    <property name="suffix" value=".jsp" />   
</bean>  

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
     <list> <ref bean="jsonConverter"/></list>
    </property>
</bean>

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter">
     <property name="supportedMediaTypes" value="application/json" />
</bean>

I run above application with http://localhost:8080/SpringExceptionHandling/exception/errorthis url

我使用http://localhost:8080/SpringExceptionHandling/exception/error这个 url运行上面的应用程序

But I get the following Exception

但我得到以下异常

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

com.test.core.ApplicationException
com.test.controller.ApplicationExceptionController.helloException(ApplicationExceptionController.java:19)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

I go through @ControllerAdvice exception handler method are not get calledthis link but still stuck with the same problem Please help me to get the solution.I am not getting the actual cause for this exception.

我通过@ControllerAdvice 异常处理程序方法没有被调用这个链接,但仍然遇到同样的问题请帮我找到解决方案。我没有得到这个异常的实际原因。

采纳答案by Vishal Singh

You are missing @EnableWebMvcannotation in your Exception handler. Your Exception handler should be like this.

@EnableWebMvc的异常处理程序中缺少注释。您的异常处理程序应该是这样的。

@EnableWebMvc
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({ApplicationException.class})
    public void notFount(){
        System.out.println("----------CaughtApplicationException-----------");
    }

    @ExceptionHandler({Exception.class})
    public void notFountGlobal(){
        System.out.println("----------CaughtApplicationException-----------");
    }

}

Also you need to tell exception handler method which exception you want to catch in which method. At last you can specify a method which can caught all other exception passing it Exception.class. The code snippet you post work for me. Hopefully it will resolve your problem.

您还需要告诉异常处理程序方法要在哪个方法中捕获哪个异常。最后,您可以指定一个可以捕获所有其他异常的方法,并将其传递给 Exception.class。您发布的代码片段对我有用。希望它能解决您的问题。

回答by Master Slave

You need to declared the exception so that the method can be mapped to the exception type. You have two possibilities, either state the exception as an argument

您需要声明异常,以便可以将方法映射到异常类型。您有两种可能性,要么将异常声明为参数

public void notFount(ApplicationException exception){

or

或者

add the type as a value attribute of your @ExceptionHandler annotation

将类型添加为 @ExceptionHandler 注释的值属性

 @ExceptionHandler(value = ApplicationException.class)

In addition, you most likely have a config issue, 'cause with the erroneus GlobalExceptionHandlerthat you've posted, the servlet wouldn't start-up, explicitly saying that no exception types are mapped to the method. Make sure that you're scanning the package where your GlobalExceptionHandlerresides, by the looks of things, that is most likely your issue

此外,您很可能有一个配置问题,GlobalExceptionHandler因为您发布的错误导致servlet 无法启动,并明确表示没有将异常类型映射到该方法。确保您正在扫描您GlobalExceptionHandler所在的包裹,从外观上看,这很可能是您的问题

回答by Stanley

In my case, the handler method is not called because of additional parameter in the method signature.

就我而言,由于方法签名中存在附加参数,因此不会调用处理程序方法。

Not working:

不工作:

@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e,  @RequestHeader(value = "referer", required = false) final String referer) {
    ...
}

The refererparameter is what caused the handler method not being called. The problem is solved after removing the parameter.

referer参数是导致处理程序方法不被调用的原因。去掉参数后问题解决。

Works:

作品:

@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle404(HttpServletRequest request, Exception e) {
    ...
}