如何实现Springmvc自定义异常处理器

发布时间:2020-07-08 11:20:35 作者:清晨
来源:亿速云 阅读:193

小编给大家分享一下如何实现Springmvc自定义异常处理器,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

如何实现Springmvc自定义异常处理器

当dispatchServlet接收到controller抛出的异常时,会将异常交由 HandlerExceptionResolver

异常处理器处理!我们可以创建自定义异常处理器实现该接口来处理自定义异常

1) 自定义异常类

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

2)自定义异常处理器

public class CustomHandleException implements HandlerExceptionResolver {
 
  @Override
  public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
      Exception exception) {
    // 定义异常信息
    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;
  }
}

3)在springmvc.xml中配置异常处理器

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

4)定制错误页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
  <h2>系统发生异常了!</h2>
  <br />
  <h2>异常信息</h2>
  <br />
  <h3>${msg }</h3>
 
</body>
</html>

5)测试异常处理

@RequestMapping(value = "/item/itemlist.action")
public ModelAndView itemList() throws MyException{
    
    List<Items> list = itemService.selectItemsList();
    
    if(true){
      throw new MyException("商品列表不能为空!!");
    }
    
    ModelAndView mav = new ModelAndView();
    mav.addObject("itemList", list);
    mav.setViewName("itemList");
    return mav;
  }

看完了这篇文章,相信你对如何实现Springmvc自定义异常处理器有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. SpringMVC框架如何实现Handler处理器
  2. Java如何实现自定义异常类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring mvc 自定义

上一篇:pytorch如何加载自己的图像数据集

下一篇:装饰设计模式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》