SpringBoot------全局异常捕获和自定义异常
1.添加Maven依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>top.ytheng</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.添加自定义异常类
package top.ytheng.demo.domain;
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
}
private String code;
private String msg;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
3.添加异常处理类
package top.ytheng.demo.domain; import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView; //如果返回的是Json格式的数据,
//可以使用@ResponseBody+@ControllerAdvice替换@RestControllerAdvice
@RestControllerAdvice
//@ControllerAdvice
public class CustomExtHandler {
private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); //捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
//@ResponseBody
public Object handleException(Exception e, HttpServletRequest request) {
LOG.error("msg:{},url:{}", e.getMessage(), request.getRequestURL()); Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
} //自定义异常
//需要添加thymeleaf依赖
//路径:src/main/resources/templates/error.html
@ExceptionHandler(value=MyException.class)
public Object handleMyException(MyException e, HttpServletRequest request) {
//返回Json数据,由前端进行界面跳转
//Map<String, Object> map = new HashMap<>();
//map.put("code", e.getCode());
//map.put("msg", e.getMsg());
//map.put("url", request.getRequestURL());
//return map; //进行页面跳转
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMsg());
return modelAndView;
}
}
4.添加异常控制器
package top.ytheng.demo.controller; import java.util.HashMap;
import java.util.Map; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import top.ytheng.demo.domain.MyException; @RestController
@RequestMapping("/exce")
public class ExceptionController { @RequestMapping("/api/v1/exce")
public Object testException() {
Map<String, Object> map = new HashMap<>();
map.put("name", "ytheng");
map.put("pwd", 123456); int data = 1/0;
return map;
} @RequestMapping("/api/v1/myexce")
public Object testMyException() { throw new MyException("500", "my ext异常"); }
}
5.添加启动类
package top.ytheng.demo; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //等于下面3个
//@SpringBootConfiguration
//@EnableAutoConfiguration
//@ComponentScan
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }
6.添加文件配置application.properties
#端口号
server.port=8090 #当前项目根目录下创建爱你日志文件
logging.file=C:\\Users\\tianheng\\eclipse-workspace\\springboot.log
7.添加error.html界面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>错误信息界面</h1>
</body>
</html>
8.右键Run As启动项目,访问地址
http://localhost:8090/exce/api/v1/exce
http://localhost:8090/exce/api/v1/myexce
另附:

SpringBoot------全局异常捕获和自定义异常的更多相关文章
- springboot 全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler
前言 本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用 ...
- Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获
一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.ex ...
- SpringBoot全局异常拦截
SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...
- 【快学springboot】5.全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- SpringBoot图文教程15—项目异常怎么办?「跳转404错误页面」「全局异常捕获」
有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1-Spr ...
- springboot(二 如何访问静态资源和使用模板引擎,以及 全局异常捕获)
在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /static / ...
- springboot编程之全局异常捕获
springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler( ...
- SpringBoot 全局异常拦截捕获处理
一.全局异常处理 //Result定义全局数据返回对象 package com.xiaobing.demo001.domain; public class Result { private Integ ...
- 测试开发专题:spring-boot统一异常捕获
java异常介绍 异常时相对于return的一种退出机制,可以由系统触发,也可由程序通过throw语句触发,异常可以通过try/catch语句进行捕获并处理,如果没有捕获,则会导致程序退出并输出异常栈 ...
随机推荐
- getOutputStream() has already been called for this response解释以及解决方法
异常:getOutputStream() has already been called for this response 的解决方法 今天在第一次接触使用“验证码”功能时,在执行时出现了异常信息: ...
- 斗鱼宣布获C轮15亿融资 直播行业进入资本时代
今天,斗鱼直播宣布完成C轮15亿人民币融资,本轮融资由凤凰投资与腾讯领投,深创投.国家中小企业基金.红土成长等跟投.2016年3月,斗鱼曾获得1亿美元(约合6.7亿元人民币)B轮融资,腾讯出资4亿人民 ...
- 关于“UI线程”
http://www.cppblog.com/Streamlet/archive/2013/05/05/199999.html 缘起 这是一篇找喷的文章. 由于一些历史原因和人际渊源,周围同事谈论一些 ...
- [How To] TrueCrypt使用教學 - 重要資訊的加密保險箱(转)
我在2013年八月的時候寫了這篇關於TrueCrypt的使用教學,但從去年(2014)五月下旬開始,TrueCrypt的首頁出現了"Using TrueCrypt is not secure ...
- UVA 12293 - Box Game(博弈)
UVA 12293 - Box Game 题目链接 题意:两个盒子,一開始一个盒子有n个球.一个仅仅有1个球,每次把球少的盒子中球消掉,把多的拿一些球给这个盒子.最后不能操作的输(球不能少于1个),A ...
- LeetCode Permutations问题详解
题目一 permutations 题目描述 Given a collection of numbers, return all possible permutations. For example,[ ...
- What is `^M` and how do I get rid of it?
When I open the file in vim, I am seeing strange ^M characters. Unfortunately, the world's favorite ...
- 高性能Javascript(2) DOM编程
第三部分 DOM编程 文档对象模型(DOM)是一个独立于语言的,使用XML和HTML文档操作的应用程序接口(API).在浏览器中,主要与HTML文档打交道,在网页应用中检索XML文档也很常见.DOM ...
- Gradle环境变量的配置
配置GRADLE_HOME: 找到Android Studio中gradle的位置 E:\Android_Studio\gradle\gradle-2.10 配置GRADLE_USER_HOME: 找 ...
- Redis高可用详解:持久化技术及方案选择
文章摘自:https://www.cnblogs.com/kismetv/p/9137897.html 前言 在上一篇文章中,介绍了Redis的内存模型,从这篇文章开始,将依次介绍Redis高可用相关 ...