gpt4 book ai didi

exception-handling - Struts 2 - 如何将异常类型的异常重定向到特定页面,但不处理特定异常?

转载 作者:行者123 更新时间:2023-12-04 07:58:35 24 4
gpt4 key购买 nike

我希望将所有类型为 Exception 的错误重定向到结果“error”。为此,我这样做了:

<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>

但我不想处理特定的异常,特别是 org.springframework.security.access.AccessDeniedException 应该被允许进一步传播。我怎样才能做到这一点?

最佳答案

使用 instanceof 运算符并从异常处理程序中重新抛出所需的异常。

我用拦截器管理它(这是我用来尝试的):

package com.kenmcwilliams.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Rethrower implements Interceptor{
@Override
public void destroy() {
}

@Override
public void init() {
}

@Override
public String intercept(ActionInvocation invocation){
System.out.println("Start rethrower!");
String result = "success";
try {
result = invocation.invoke();
} catch (Exception ex) {
Logger.getLogger(Rethrower.class.getName()).log(Level.SEVERE, null, ex);
}
Object exception = ActionContext.getContext().getValueStack().findValue("exception");
if (exception instanceof RuntimeException){
System.out.println("DOING RETHROW!");
RuntimeException e = (RuntimeException)exception;
throw e;
}
System.out.println("After rethrower!");
return result;
}
}

这是 struts.xml(以节省查找 struts dtd 的时间):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.ui.theme" value="simple" />
<package name="kenmcwilliams" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="rethrower" class="com.kenmcwilliams.interceptor.Rethrower"/>
<interceptor-stack name="rethrow-stack">
<interceptor-ref name="rethrower"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<global-results>
<result name="error" >/WEB-INF/content/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
<action name="mybomb" class="com.kenmcwilliams.kensocketchat.action.Bomb">
<interceptor-ref name="rethrow-stack"/>
<result>/WEB-INF/content/bomb.jsp</result>
</action>
</package>
</struts>

最后是 Action (它只是抛出一个运行时异常):

package com.kenmcwilliams.kensocketchat.action;

import com.opensymphony.xwork2.ActionSupport;

public class Bomb extends ActionSupport{
@Override
public String execute() throws Exception{
throw new RuntimeException();
}
}

关于exception-handling - Struts 2 - 如何将异常类型的异常重定向到特定页面,但不处理特定异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10313279/

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