SpringMVC之异常处理

本文详细介绍了在SpringMVC框架下如何处理异常,包括自定义异常类、Controller层异常抛出、使用SimpleMappingExceptionResolver进行异常信息的统一处理和维护。通过具体代码示例,展示了异常处理的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、 异常处理思路

系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护

 二、异常处理

1.Controller层抛出异常

@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() {
	// 查询商品数据
	List<Item> list = this.itemService.queryItemList();
        if(list == null){
            throw new CustomeException("查询信息不存在!");
        }

	// 运行时异常
	int a = 1 / 0;

 
	// 创建ModelAndView,设置逻辑视图名
	ModelAndView mv = new ModelAndView("itemList");
 
	// 把商品数据放到模型中
	mv.addObject("itemList", list);
	return mv;
}

2.自定义异常类 CustomException 

//定义一个简单的异常类
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;
    }

}

3. 使用Spring MVC提供的简单异常处理器 SimpleMappingExceptionResolver

  异常信息的统一处理和维护

public class CustomHandleException implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
            Exception ex) {
    // 发生异常地方  Service层 方法  包名+类名+方法名(形参)  的一个字符串
    // 定义异常信息
	String msg;

		// 判断异常类型
	if (exception instanceof MyException) {
			// 如果是自定义异常,读取异常信息
		msg = exception.getMessage();
	} else {
		// 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息
		Writer out = new StringWriter();
		PrintWriter s = new PrintWriter(out);
		exception.printStackTrace(s);
		msg = out.toString();
	}


	// 把错误信息发给相关人员,邮件,短信等方式
	// TODO

	// 返回错误页面,给用户友好页面显示错误信息
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addObject("msg", msg);
	modelAndView.setViewName("error");

	return modelAndView;
    }

}

4. 配置spring-mvc.xml文件加入异常处理器

<!-- 配置全局异常处理器 -->
<bean id="customHandleException" class="cn.mark.ssm.exception.CustomHandleException"/>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值