全局异常处理器开发

作者: 小小蒜头 | 来源:发表于2017-12-11 18:06 被阅读201次

一、异常的分类

1. 预期异常 通过捕获异常从而获取异常信息
2. 运行时异常RuntimeException 主要通过规范代码开发、测试通过手段减少运行时异常的发生

系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

流程

springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。

二、自定义异常类

对不同的异常类型定义异常类,继承Exception。

package com.eurasia.exception;

/**
 * Created by yvettee on 2017/12/11.
 * 针对预期的异常,需要在程序中抛出此类的异常
 */
public class CustomException extends Exception {

    //异常信息
    private String message;

    public CustomException() {
        super();
    }

    public CustomException(String message) {this.message = message;
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

三、全局异常处理器

思路:系统遇到异常,在程序中手动抛出,dao抛给service、service给controller、controller抛给前端控制器,前端控制器调用全局异常处理器。
全局异常处理器处理思路:解析出异常类型

  • 如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示。
  • 如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)

springmvc提供一个HandlerExceptionResolver接口。

package com.eurasia.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Title: CustomExceptionResolver</p>
 * <p>Description:全局异常处理器 </p>
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {

    /**
     * (非 Javadoc)
     * <p>Title: resolveException</p>
     * <p>Description: </p>
     *
     * @param request
     * @param response
     * @param handler
     * @param ex       系统 抛出的异常
     * @return
     * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        //handler就是处理器适配器要执行Handler对象(只有method)
//      解析出异常类型
//      如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示
//      String message = null;
//      if(ex instanceof CustomException){
//          message = ((CustomException)ex).getMessage();
//      }else{
////            如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
//          message="未知错误";
//      }

        //上边代码变为
        CustomException customException = null;
        if (ex instanceof CustomException) {
            customException = (CustomException) ex;
        } else {
            customException = new CustomException("未知错误");
        }
        //错误信息
        String message = customException.getMessage();

        ModelAndView modelAndView = new ModelAndView();

        //将错误信息传到页面
        modelAndView.addObject("message", message);
        //指向错误页面
        modelAndView.setViewName("error");

        return modelAndView;
    }
}

四、错误页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>错误页面</title>
</head>
<body>
${message}
</body>
</html>

五、在springmvc.xml配置全局异常处理器

<!-- 全局异常处理器
    只要实现HandlerExceptionResolver接口就是全局异常处理器
     -->
    <bean class="com.eurasia.exception.CustomExceptionResolver"></bean>

六、异常测试

在controller、service、dao中任意一处需要手动抛出异常。
如果是程序中手动抛出的异常,在错误页面中显示自定义的异常信息,如果不是手动抛出异常说明是一个运行时异常,在错误页面只显示“未知错误”。

在商品修改的controller方法中抛出异常:

public String editItems(Model model, @RequestParam(value = "id", required = true) Integer items_id) throws Exception {
        //调用service根据id查询商品信息
        ItemsCustom itemsCustom = itemsService.findItemsById(items_id);

        //判断商品是否为空,抛出异常
        if (itemsCustom == null){
            throw new CustomException("修改的商品信息不存在");
        }

//        modelAndView.setViewName("/items/editItems");
        //通过形参中的model将model数据传到页面,modelAndView.addObject("itemsCustom", itemsCustom);
        model.addAttribute("itemsCustom", itemsCustom);
        return "/items/editItems";
    }

在service接口中抛出异常:

public ItemsCustom findItemsById(Integer id) throws Exception {
        Items items = itemsMapper.selectByPrimaryKey(id);
        if(items==null){
            throw new CustomException("修改的商品信息不存在!");
        }
     //......此处省略
    }
  • 如果与业务功能相关的异常,建议在service中抛出异常。
  • 与业务功能没有关系的异常,建议在controller中抛出。

上边的功能,建议在service中抛出异常

上篇:注解开发validation校验
下篇:上传图片
源代码:https://github.com/yvettee36/SpringMVC_mybatis

相关文章

网友评论

    本文标题:全局异常处理器开发

    本文链接:https://www.haomeiwen.com/subject/fxwiixtx.html