SpringBoot配置全局的异常捕获

需要以下两个类配合完成:

IoExceptionHandler.java(异常助手类)
IMoocJSONResult.java(实体类)
package com.blog.pojo;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import java.util.List;

public class IMoocJSONResult {
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 响应业务状态
    private Integer status;

    // 响应消息
    private String msg;

    // 响应中的数据
    private Object data;

    private String ok; // 不使用

    public static IMoocJSONResult build(Integer status, String msg, Object data) {
        return new IMoocJSONResult(status, msg, data);
    }

    public static IMoocJSONResult ok(Object data) {
        return new IMoocJSONResult(data);
    }

    public static IMoocJSONResult ok() {
        return new IMoocJSONResult(null);
    }

    public static IMoocJSONResult errorMsg(String msg) {
        return new IMoocJSONResult(500, msg, null);
    }

    public static IMoocJSONResult errorMap(Object data) {
        return new IMoocJSONResult(501, "error", data);
    }

    public static IMoocJSONResult errorTokenMsg(String msg) {
        return new IMoocJSONResult(502, msg, null);
    }

    public static IMoocJSONResult errorException(String msg) {
        return new IMoocJSONResult(555, msg, null);
    }

    public IMoocJSONResult() {

    }

// public static LeeJSONResult build(Integer status, String msg) {
// return new LeeJSONResult(status, msg, null);
// }

    public IMoocJSONResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public IMoocJSONResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    /**
     *
     * @Description: 将json结果集转化为LeeJSONResult对象
     * 需要转换的对象是一个类
     * @param jsonData
     * @param clazz
     * @return
     *
     * @author leechenxiang
     * @date 2016年4月22日 下午8:34:58
     */
    public static IMoocJSONResult formatToPojo(String jsonData, Class<?> clazz) {
        try {
            if (clazz == null) {
                return MAPPER.readValue(jsonData, IMoocJSONResult.class);
            }
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (clazz != null) {
                if (data.isObject()) {
                    obj = MAPPER.readValue(data.traverse(), clazz);
                } else if (data.isTextual()) {
                    obj = MAPPER.readValue(data.asText(), clazz);
                }
            }
            return build(jsonNode.get("status").getIntValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     *
     * @Description: 没有object对象的转化
     * @param json
     * @return
     *
     * @author leechenxiang
     * @date 2016年4月22日 下午8:35:21
     */
    public static IMoocJSONResult format(String json) {
        try {
            return MAPPER.readValue(json, IMoocJSONResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @Description: Object是集合转化
     * 需要转换的对象是一个list
     * @param jsonData
     * @param clazz
     * @return
     *
     * @author leechenxiang
     * @date 2016年4月22日 下午8:35:31
     */
    public static IMoocJSONResult formatToList(String jsonData, Class<?> clazz) {
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (data.isArray() && data.size() > 0) {
                obj = MAPPER.readValue(data.traverse(),
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return build(jsonNode.get("status").getIntValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

    public String getOk() {
        return ok;
    }

    public void setOk(String ok) {
        this.ok = ok;
    }
}
package com.blog.util;

import com.blog.pojo.IMoocJSONResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

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

@ControllerAdvice
public class IoExceptionHandler { 
    //错误页面路径
    private final static  String IMOOC_ERROR_VIEW =  "/homepage/404";

    @ExceptionHandler(value=Exception.class)
    public  Object  errorHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws Exception{

                 e.printStackTrace();

                 if(isAjax(request)){
                     return  IMoocJSONResult.errorException(e.getMessage());
                 } else {
                     ModelAndView mav = new ModelAndView();
                     //返回错误异常
                     mav.addObject("exception",e);
                     //返回错误方法的路径
                     mav.addObject("url",request.getRequestURL());
                     //返回错误页面路径
                     mav.setViewName(IMOOC_ERROR_VIEW);
                     return mav;

                 }
    }

    /*
    * 判断异常是否是ajax异常
    * */
    public static boolean isAjax(HttpServletRequest httpRequest){
        return (httpRequest.getHeader("X-Requested-With") !=null && "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString() ) );
    }
}

 

下面测试一下:

404.html

<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>404错误!很抱歉,您要找的页面不存在</title>
<link rel="stylesheet" type="text/css" href="/homepage/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/homepage/css/nprogress.css">
<link rel="stylesheet" type="text/css" href="/homepage/css/style.css">
<link rel="stylesheet" type="text/css" href="/homepage/css/font-awesome.min.css">
<link rel="apple-touch-icon-precomposed" href="/homepage/images/icon/icon.png">
<link rel="shortcut icon" href="/homepage/images/icon/favicon.ico">
<script src="/homepage/js/jquery-2.1.4.min.js"></script>
<script src="/homepage/js/nprogress.js"></script>
<script src="/homepage/js/jquery.lazyload.min.js"></script>
<!--[if gte IE 9]>
  <script src="/homepage/js/jquery-1.11.1.min.js" type="text/javascript"></script>
  <script src="/homepage/js/html5shiv.min.js" type="text/javascript"></script>
  <script src="/homepage/js/respond.min.js" type="text/javascript"></script>
  <script src="/homepage/js/selectivizr-min.js" type="text/javascript"></script>
<![endif]-->
<!--[if lt IE 9]>
  <script>window.location.href='upgrade-browser.html';</script>
<![endif]-->
<style type="text/css">
.panel{
	padding:80px 20px 0px;
	min-height:500px;
	cursor:default;
}
.text-center {
	margin:0 auto;
    text-align: center;
	border-radius:10px;
	max-width:900px;
	-moz-box-shadow: 0px 0px 5px rgba(0,0,0,.3);
	-webkit-box-shadow: 0px 0px 5px rgba(0,0,0,.3);
	box-shadow: 0px 0px 5px rgba(0,0,0,.1);
	
}
.float-left {
    float: left !important;
}
.float-right {
    float: right !important;
}
img {
    border: 0;
    vertical-align: bottom;
}
h2 {
    padding-top: 20px;
	font-size: 20px;
}
.padding-big {
    padding: 20px;
}
.alert {
    border-radius: 5px;
    padding: 15px;
    border: solid 1px #ddd;
    background-color: #f5f5f5;
}
</style>
</head>

<body class="user-select">
<header class="header">
  <nav class="navbar navbar-default" id="navbar">
    <div class="container">
      <div class="header-topbar hidden-xs link-border">
        <ul class="site-nav topmenu">
          <li><a href="tags.html">标签云</a></li>
          <li><a href="readers.html" rel="nofollow">读者墙</a></li>
          <li><a href="links.html" rel="nofollow">友情链接</a></li>
          <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" rel="nofollow">关注本站 <span class="caret"></span></a>
            <ul class="dropdown-menu header-topbar-dropdown-menu">
              <li><a data-toggle="modal" data-target="#WeChat" rel="nofollow"><i class="fa fa-weixin"></i> 微信</a></li>
              <li><li><a href="//shang.qq.com/wpa/qunwpa?idkey=225f72ba399ffadea6d01bb6c597bcb30a3ce14999d150746212d6646a5c4933" rel="nofollow"><i class="fa fa-qq"></i> QQ</a></li>
              <li><a data-toggle="modal" data-target="#areDeveloping" rel="nofollow"><i class="fa fa-rss"></i> RSS</a></li>
            </ul>
          </li>
        </ul>
        <a href="javascript:;" class="login" rel="nofollow">Hi,您好~</a> </div>
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#header-navbar" aria-expanded="false"> <span class="sr-only"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button></li>
        <h1 class="logo hvr-bounce-in"><a href="/blog/index" title=""><img src="/homepage/images/logo.png" alt=""></a></h1>
      </div>
      <div class="collapse navbar-collapse" id="header-navbar">
        <ul class="nav navbar-nav navbar-right">
          <li class="hidden-index active"><a data-cont="首页" href="/blog/index">首页</a></li>
          <li><a href="/blog/procedure">程序</a></li>
          <li><a href="/blog/life">人生</a></li>
        </ul>
        <form class="navbar-form visible-xs" action="/Search" method="post">
          <div class="input-group">
            <input type="text" name="keyword" class="form-control" placeholder="请输入关键字" maxlength="20" autocomplete="off">
            <span class="input-group-btn">
            <button class="btn btn-default btn-search" name="search" type="submit">搜索</button>
            </span> </div>
        </form>
      </div>
    </div>
  </nav>
</header>
<section class="container">
  <div class="panel">
    <div class="text-center">
      <h2><stong>404错误!很抱歉,您要找的页面不存在</stong></h2>
      <div th:text="${url}"></div>
      <div th:text="${exception.message}"></div>
      <div>
        <div class="float-left"> <img src="/homepage/images/404/left.gif" alt="" />
          <div class="alert"> 卧槽!页面不见了! </div>
        </div>
        <div class="float-right"> <img src="/homepage/images/404/right.png" width="260" class="hidden-xs" alt="" /> </div>
      </div>
      <div class="padding-big"> <a href="/blog/index" class="btn btn-primary">返回首页</a> <a href="" class="btn btn-default">保证不打死管理员</a> </div>
    </div>
  </div>
</section>
<footer class="footer">
  <div class="container">
    <p>&copy; 2016 <a href="">ylsat.com</a> &nbsp; <a href="#" target="_blank" rel="nofollow">豫ICP备20151109-1</a> &nbsp; &nbsp; <a href="http://www.mycodes.net/" target="_blank">源码之家</a></p>
  </div>
  <div id="gotop"><a class="gotop"></a></div>
</footer>
<!--微信二维码模态框-->
<div class="modal fade user-select" id="WeChat" tabindex="-1" role="dialog" aria-labelledby="WeChatModalLabel">
  <div class="modal-dialog" role="document" style="margin-top:120px;width:280px;">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="WeChatModalLabel" style="cursor:default;">微信扫一扫</h4>
      </div>
      <div class="modal-body" style="text-align:center"> <img src="/homepage/images/weixin.jpg" alt="" style="cursor:pointer"/> </div>
    </div>
  </div>
</div>
<!--该功能正在日以继夜的开发中-->
<div class="modal fade user-select" id="areDeveloping" tabindex="-1" role="dialog" aria-labelledby="areDevelopingModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="areDevelopingModalLabel" style="cursor:default;">该功能正在日以继夜的开发中…</h4>
      </div>
      <div class="modal-body">
        <img src="/homepage/images/baoman/baoman_01.gif" alt="深思熟虑" /><p style="padding:15px 15px 15px 100px; position:absolute; top:15px; cursor:default;">很抱歉,程序猿正在日以继夜的开发此功能,本程序将会在以后的版本中持续完善!</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">朕已阅</button>
      </div>
    </div>
  </div>
</div>
<!--<div id="rightClickMenu">
  <ul class="list-group rightClickMenuList">
    <li class="list-group-item disabled">欢迎访问博客</li>
    <li class="list-group-item"><span>IP:</span>172.16.10.129</li>
    <li class="list-group-item"><span>地址:</span>河南省郑州市</li>
    <li class="list-group-item"><span>系统:</span>Windows10 </li>
    <li class="list-group-item"><span>浏览器:</span>Chrome47</li>
  </ul>
</div>-->
<script src="/homepage/js/bootstrap.min.js"></script>
<script src="/homepage/js/jquery.ias.js"></script>
<script src="/homepage/js/scripts.js"></script>
</body>
</html>

controller:

    
@Controller
@RequestMapping(value={"/blog"}
public class BlogController{

@RequestMapping(value = {"/error"})
    public String error(){
         int a = 1/0;
         return "404";
    }

}

 

 此时启动工程,输入localhost/blog/error,因为1/0是错误的,所以跳转到错误页面,并显示错误方法和错误代码,至此异常捕捉成功。

在 Spring Boot 中,可以通过自定义全局异常处理器来捕获和处理应用程序中的异常。以下是一种常见的实现方式: 首先,创建一个全局异常处理器类,例如 `GlobalExceptionHandler`,并使用 `@ControllerAdvice` 注解将其标记为全局异常处理器。在类中可以定义多个方法来处理不同类型的异常。 ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { // 处理异常逻辑 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error"); } @ExceptionHandler(MyCustomException.class) public ResponseEntity<String> handleMyCustomException(MyCustomException ex) { // 处理自定义异常逻辑 return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); } // 其他异常处理方法... } ``` 在以上代码中,`@ExceptionHandler` 注解用于指定每个方法要处理的异常类型。在方法中,你可以根据具体需求编写异常处理逻辑,并返回合适的响应。 需要注意的是,全局异常处理器类需要被扫描到,可以通过将其所在的包作为扫描路径配置到 Spring Boot 的配置文件中,或者使用 `@ComponentScan` 注解进行手动配置。 另外,还可以通过实现 `ErrorController` 接口来处理 Spring Boot 应用程序中无法被 `GlobalExceptionHandler` 捕获的错误。 这样,当应用程序中发生异常时,全局异常处理器会捕获并处理它们,返回相应的错误信息给客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值