gpt4 book ai didi

java - @ControllerAdvice 不处理异常

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:55 24 4
gpt4 key购买 nike

我已经浏览了所有相关的帖子,但我的@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 与 Controller 位于同一包中。

最佳答案

您需要对 @ControllerAdvice 异常实现“Ordered”,并使用 Ordered 接口(interface)的 getOrder 方法返回订单。

顺序越低,优先级越高。这样,您可以首先捕获响应实体异常并在全局异常处理程序捕获它们之前对其进行处理。

关于java - @ControllerAdvice 不处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24581392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com