sta*_*low 4 java error-handling spring exception-handling
我有以下内容
web.xml中
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/views/errorPages/500.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/views/errorPages/error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/views/errorPages/500.jsp</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)
弹簧的context.xml
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
</bean>
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.company.server.exception.GenericException">GenericExceptionPage</prop>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
<property name="defaultErrorView" value="defaulterror"></property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
GenericException.java
public class GenericException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private String customMsg;
public String message;
public String getCustomMsg()
{
return customMsg;
}
public void setCustomMsg(String customMsg)
{
this.customMsg = customMsg;
}
public GenericException(String customMsg)
{
this.customMsg = customMsg;
}
@Override
public String getMessage()
{
return message;
}
}
Run Code Online (Sandbox Code Playgroud)
myController.java
@Controller
@RequestMapping(value = "/admin/store")
public class AdminController
{
//bunch of restful drivin requestMappings
}
Run Code Online (Sandbox Code Playgroud)
问题:如何获取任何和所有内部服务器错误和异常以向单个页面显示异常/错误消息?
nic*_*ild 11
我会考虑@ExceptionHandler在我的控制器中的方法上使用注释.这个注释标记了一个方法,当一个Exception气泡向上通过控制器时,它将被Spring调用.
这样,当你的一个@RequestMapping方法抛出一个Exception,然后将调用此方法并返回您想要的任何错误消息.
public class BaseController {
@ExceptionHandler(Throwable.class)
public String handleException(Throwable t) {
return "redirect:/errorPages/500.jsp";
}
@ExceptionHandler(Exception.class)
public String handleException(Throwable t) {
return "redirect:/errorPages/error.jsp";
}
}
@Controller
@RequestMapping(value = "/admin/store")
public class AdminController extends BaseController
{
@RequestMapping(...)
//Some method
@RequestMapping(...)
//Another method
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8879 次 |
| 最近记录: |