Spring Boot 知识笔记(全局异常)
通过ControllerAdvice和ExceptionHandler捕获异常和错误信息,向前端返回json格式的状态码及异常描述信息。
1、新建一个Controller,抛出一个异常。
package net.xdclass.demo.controller; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class ExcpController {
@GetMapping("/api/v1/test_excp")
public Object testExcp(){
throw new RuntimeException("exception1");
}
}
2、未捕获异常的时候,访问这个接口的时候,收到的异常如下
{
"timestamp": "2019-06-03T11:11:41.548+0000",
"status": 500,
"error": "Internal Server Error",
"message": "exception1",
"trace": "java.lang.RuntimeException: exception1\r\n\tat net.xdclass.demo.controller.ExcpController.testExcp(ExcpController.java:11)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:634)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\n",
"path": "/api/v1/test_excp"
}
3、新建一个异常处理类
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map; @RestControllerAdvice public class CustomExtHandler {
// private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
@ExceptionHandler(value = Exception.class) //需要捕获异常事件的类型
public Object handException(Exception e, HttpServletRequest request){
// LOG.error("url {}, msg {}",request.getRequestURL(),e.getMessage());
Map<String,Object> map = new HashMap<>();
map.put("code",100);
map.put("msg",e.getMessage());
map.put("url",request.getRequestURL());
return map;
}
}
@RestControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类
@ExceptionHander一直监听,捕获异常后按下面的方法处理
4、其他异常类型
HttpRequestMethodNotSupportedException |
http请求的方法不正确 |
MissingServletRequestParameterException |
请求参数不全 |
TypeMismatchException |
请求参数类型不正确 |
DataFormatException |
数据格式不正确 |
UserNotFoundException |
用户没找到 |
IllegalArgumentException |
非法输入 |
5、自定义异常
新建自定义异常类
ackage net.xdclass.demo.domain; public class MyException extends Exception{
String code;
String msg;
public MyException(String code,String msg){
this.code=code;
this.msg=msg;
} public String getCode() {
return code;
} public String getMsg() {
return msg;
} public void setCode(String code) {
this.code = code;
} public void setMsg(String msg) {
this.msg = msg;
}
}
新建一个controller抛出自定义异常
package net.xdclass.demo.controller; import net.xdclass.demo.domain.MyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class ExcptionController {
@RequestMapping("/api/v1/text_text")
public Object index() throws MyException {
throw new MyException("500","wrong!!!");
}
}
Exceptionhandler捕捉自定义异常
ackage net.xdclass.demo.domain; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map; @RestControllerAdvice public class CustomExtHandler {
// private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
@ExceptionHandler(value = Exception.class) //需要捕获异常事件的类型 //捕获自定义异常事件
@ExceptionHandler(value = MyException.class)
public Object myException(MyException e,HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
map.put("code",e.getCode());
map.put("msg",e.getMsg());
return map;
}
}
运行后的结果
6、返回一个自定义错误页面
资源文件中增加myerror.html
@RestControllerAdvice 修改为@ControllerAdvice
package net.xdclass.demo.domain; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.springframework.http.HttpRequest;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map; @ControllerAdvice public class CustomExtHandler {
// private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
@ResponseBody
@ExceptionHandler(value = Exception.class) //需要捕获异常事件的类型
public Object handException(Exception e, HttpServletRequest request){
// LOG.error("url {}, msg {}",request.getRequestURL(),e.getMessage());
Map<String,Object> map = new HashMap<>();
map.put("code",100);
map.put("msg",e.getMessage());
map.put("url",request.getRequestURL());
return map;
} //捕获自定义异常事件,返回html页面
@ExceptionHandler(value = MyException.class)
public Object myException(MyException e,HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("myerror.html");
modelAndView.addObject("msg",e.getMsg());
return modelAndView;
} }
执行结果
Spring Boot 知识笔记(全局异常)的更多相关文章
- Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json
需求 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": {}, "msg": ...
- 在Spring Boot中添加全局异常捕捉提示
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...
- Spring Boot 知识笔记(整合Mybatis)
一.pom.xml中添加相关依赖 <!-- 引入starter--> <dependency> <groupId>org.mybatis.spring.boot&l ...
- Spring Boot 知识笔记(配置文件)
Spring boot 提供了两种常用的配置文件,properties和yml文件. 1.yml yml是YAML(YAML Ain't Markup Language)语言的文件,以数据为中心,比j ...
- Spring Boot 知识笔记(热部署)
热部署原理: 使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为restart ClassLoader ...
- Spring Boot 知识笔记(创建maven项目、HTTP接口)
一.使用Maven手工创建SpringBoot应用(IDEA) 1. 点击File——New——Project——Maven——Next,填写相关信息,创建项目. 2. 在pom.xml中添加相关 ...
- Spring Boot 知识笔记(thymleaf模板引擎)
一.pom.xml中引入 <dependency> <groupId>org.springframework.boot</groupId> <artifact ...
- Spring Boot 知识笔记(整合Redis)
一.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...
- Spring Boot 知识笔记(servlet、监听器、拦截器)
一.通过注解自定义servlet package net.Eleven.demo.servlet; import javax.servlet.ServletException; import java ...
随机推荐
- 『Pushbox 点双联通分量』
Pushbox Description 周婧涵和她的小伙伴们发明了一个新游戏.游戏名字很准确,但不是特别有 创意.她们称之为"推动箱子在谷仓周围找到正确的位置,不要移动干草"游戏 ...
- JavaScriptCore在浏览器引擎中的位置
因为随着JS这门语言的发展,JS的宿主越来越多,有各种各样的浏览器,甚至是常见于服务端的Node.js(基于V8运行). 2. Webkit 源代码由三大模块组成: 1). WebCore ...
- 关于YII框架Response content must not be an array的解决方法
public function actionGet_permissions() { \Yii::$app->response->format = \yii\web\Response::FO ...
- 关于插件Markdown Preview Enhanced的使用技巧
目录 1.关于TOC 2.关于转义符 3.绘图 3.0 绘图配色主题 3.1 Flowchart(流程图) 3.2 Sequence diagram(顺序图) 3.4 保存为HTML shanzm 1 ...
- sql 简单分页查询(ror_number() over)
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY ID DESC ) AS r_num FROM (select * from #table ...
- (fiddler+loadrunner) fiddler抓包后转化为loadrunner脚本
众所周知,LR的各种浏览器不能正常弹出,以及脚本中的手工转译一直是困扰着广大性能测试工程师的一大问题. 我在做一个HTTP接口性能测试时,需要上报大量的json数据,这时使用LR进行脚本编写后然后自己 ...
- Mac下Appnium的Android的UI自动化环境搭建
1. 安装jdk:略 检查是否安装:执行命令java -version admindeMacBook-Pro-2:~ $ java -version java version "1.8.0_ ...
- Unity Ioc 依赖倒置及Untity AOP被动拦截/自动拦截
各位博友金安,首先声明这是一篇转载的博客,原文链接:https://www.cnblogs.com/scottpei/archive/2013/01/08/2851087.html 十年河东,十年河西 ...
- Java 之 Stack 集合
一.Stack:栈 概述 栈是一种先进后出(FILO)或后进先出(LIFO:Last in first out)的数据结构. Stack是Vector的子类,比Vector多了几个方法,它的后进先出的 ...
- SpringBoot集成JWT
JWT(json web tokens)是目前比较流行的跨域认证解决方案:说通俗点就是比较流行的token生成和校验的方案.碰巧公司有个app的项目的token采用了jwt方案,因此记录下后端 ...