您的位置:首页 > 编程语言 > Java开发

springmvc统一异常处理

2017-11-15 18:52 267 查看
springmvc统一异常处理

方式一:

1.springmvc配置文件中

<!-- springmvc提供的简单异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义默认的异常处理页面-->
<property name="defaultErrorView" value="jsp/error.jsp"/>
<!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
<property name="exceptionAttribute" value="ex"/>
<!-- 定义需要特殊处理的异常,这是重要点-->
<property name="exceptionMappings">
<props>
<prop key="xx.exception.CustomException">/jsp/custom_error.jsp</prop>
</props>
<!-- 还可以定义其他的自定义异常-->
</property>
</bean>

2.定义一个简单的异常类

public class CustomException extends Exception {
//异常信息
public String message;
public CustomException(String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

方法二

注解异常处理@ControllerAdvice

@ExceptionHandler中定义指定的异常类 ,没有定义全部获取异常

@ControllerAdvice
public class AdviceController {
@ExceptionHandler(value={CustomException.class,ArithmeticException.class,IncorrectResultSetColumnCountException.class,IndexOutOfBoundsException.class})
public String doException(Model model,Exception ex){
if(ex instanceof CustomException){
System.out.println("异常信息: "+ex.getMessage());
model.addAttribute("error","异常信息: "+ex.getMessage());
return "custom_error";
}if(ex instanceof ArithmeticException){
System.out.println("异常信息 : 除数不零"+ex.getMessage());
model.addAttribute("error","异常信息: "+ex.getMessage());
}else{
System.out.println("异常信息 : 系统未知错误"+ex.getMessage());
model.addAttribute("error","系统未知错误: "+ex.getMessage());
}

return "error";
}

@ExceptionHandler
public String doOneException(Model model,Exception ex){
System.out.println("异常信息 : 系统未知错误"+ex.getMessage());
model.addAttribute("error","系统未知错误: "+ex.getMessage());
return "custom_error";
}

}


404错误

<error-page>
<error-code>404</error-code>
<location>/error_404.jsp</location>
</error-page>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: