SpringMVC 异常处理配置

  1. 定义自定义异常类

     public class CustomException extends Exception {
     	private String message;
     
     	public CustomException(String message)
     	{
     		this.message = message;
     	}
     
     	public String getMessage() {
     		return message;
     	}
     }
    
  2. 定义异常处理器

     public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {
     @Override
     public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
     		Exception ex) {
     	//1.处理异常
     	CustomException customException = null;
     	//已知错误
     	if(ex instanceof CustomException)
     	{
     		customException = (CustomException)ex;
     	}
     	//未知错误
     	else
     	{
     		customException = new CustomException("未知错误"+ex.getMessage());
     	}
     	
     	//记录日志或发送邮件给管理 员,降低耦合度
     	//log();
     	//sendEmail(); 
     	
     	//2.异常处理完成之后,跳转指定页面,并且显示错误信息
     	ModelAndView mav = new ModelAndView();
     	mav.addObject("exceptionMessage", customException.getMessage());
     	mav.setViewName("WEB-INF/exception");//   /WEB-INF/exception.jsp
     	
     	return mav;
     }
    

    }

  3. 在spring-mvc.xml中配置异常处理器

     <!-- 配置全局异常处理器 -->
     <bean class="com.neuedu.exception.CustomHandlerExceptionResolver"></bean>
    
  4. 编写异常信息文件UserController、UserService、UserDao,并在UserDao的方法中抛出自定义异常

     public boolean selectUser(String username,String password) throws CustomException
     {
     	System.out.println("UserDao: " + username + "   " + password);
     	try {
     		//制造异常(检查性异常、预期异常、非运行时异常)
     		FileInputStream input = new FileInputStream(new File("file.txt"));
     		
     	} catch (FileNotFoundException e) {
     		//记录日志或发送邮件给管理 ,耦合度太高,所有的catch都需要修改,所以抛出异常,去全局异常处理器进行处理
     		//log();
     		//sendEmail(); 
     		throw new CustomException("UserDao.selectUser("+username+"," + password + "):file.txt文件找不到");
     	}
     	
     return true;
     }
    
  5. 测试
    http://localhost:8088/springMVC_06_exception/login.action?username=marry&password=111111

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值