[英]@ControllerAdvice is not handling exception
我已經瀏覽了所有相關文章,但是我的@ControllerAdvice似乎並沒有處理從Controller類拋出的自定義異常。但是@Controller類中的@ExceptionHandler確實可以處理該異常。這個錯誤。
web.xml中:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
調度員servlet.xml中:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scan base-package="com.test.controller,com.test.exception"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
@ControllerAdvice類:
package com.test.controller;
import com.test.exception.EmployeeException;
@EnableWebMvc
@ControllerAdvice
public class EmployeeExceptionController {
@ExceptionHandler(EmployeeException.class)
public ModelAndView employeeNotFound(EmployeeException ex){
String msg="employee with the "+ex.getId()+" not found";
ModelAndView mv=new ModelAndView("helloWorld");
mv.addObject("message",msg);
mv.addObject("name","boss");
return mv;
}
}
@ControllerAdvice與控制器位於同一軟件包中。
您需要對@ControllerAdvice異常實現“ Ordered”,並使用Ordered接口的getOrder方法返回訂單。
順序越低,優先級越高。 這樣,您可以先捕獲響應實體異常並在全局異常處理程序捕獲異常之前對其進行處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.