通过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 知识笔记(全局异常)的更多相关文章

  1. Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json

    需求 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0,  "data": {},  "msg": ...

  2. 在Spring Boot中添加全局异常捕捉提示

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...

  3. Spring Boot 知识笔记(整合Mybatis)

    一.pom.xml中添加相关依赖 <!-- 引入starter--> <dependency> <groupId>org.mybatis.spring.boot&l ...

  4. Spring Boot 知识笔记(配置文件)

    Spring boot 提供了两种常用的配置文件,properties和yml文件. 1.yml yml是YAML(YAML Ain't Markup Language)语言的文件,以数据为中心,比j ...

  5. Spring Boot 知识笔记(热部署)

    热部署原理: 使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为restart ClassLoader ...

  6. Spring Boot 知识笔记(创建maven项目、HTTP接口)

    一.使用Maven手工创建SpringBoot应用(IDEA) 1.  点击File——New——Project——Maven——Next,填写相关信息,创建项目. 2.  在pom.xml中添加相关 ...

  7. Spring Boot 知识笔记(thymleaf模板引擎)

    一.pom.xml中引入 <dependency> <groupId>org.springframework.boot</groupId> <artifact ...

  8. Spring Boot 知识笔记(整合Redis)

    一.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  9. Spring Boot 知识笔记(servlet、监听器、拦截器)

    一.通过注解自定义servlet package net.Eleven.demo.servlet; import javax.servlet.ServletException; import java ...

随机推荐

  1. CentOS7 安装nginx-1.14.0

    nginx源码包:http://nginx.org/en/download.html 1.安装gcc gcc是用来编译下载下来的nginx源码 yum install gcc-c++ 2.安装pcre ...

  2. [转帖]几张图让你看懂WebAssembly

    几张图让你看懂WebAssembly https://www.jianshu.com/p/bff8aa23fe4d     (图片来源:giphy.com) 编者按:本文由明非在众成翻译平台上翻译. ...

  3. ListView 实现进度条显示

    代码参考互联网,本人在Win10 + Delphi 10.3.2 社区版中测试通过,现将测试通过的代码分享如下: unit Unit1; interface uses Winapi.Windows, ...

  4. 图解微信小程序---实现页面的跳转与返回操作

    图解微信小程序---实现页面的跳转与返回操作 代码笔记 操作步骤 第一步:在app.json配置文件中,创建跳转页面 第二步:编写首页跳转(注意跳转方式,和设置点击样式类名) 第三步:编写首页样式 第 ...

  5. 【linux】Too many open files 解决问题第一步【记录】

    记录一下解决linux上出现:Too many open files  的第一步骤. 做个记录,免得每次都查来查去的. 1.查看 ulimit -a 2.修改 vi /etc/security/lim ...

  6. 在ASP.NET Core中添加的Cookie如果含有特殊字符,会被自动转义

    我们知道在Cookie中有些字符是特殊字符,这些字符是不能出现在Cookie的键值中的. 比如"="是Cookie中用来分隔键和值的特殊字符,例如:Key01=Value01,表示 ...

  7. Lambda表达式的用法

    参考:https://www.cnblogs.com/knowledgesea/p/3163725.html

  8. 选美?作秀?MES系统的选择更应该从实际出发

    MES选型不是做秀,不是选美. 如今不少企业在信息化推广应用过程中面面求好.追求完美,用意没错,然而在MES开发过程中,软件商不可能将今后各种可能出现的问题考虑周全,不可能将系统做到十全十美.随着系统 ...

  9. kubernetes学习Service之headless和statefulSet结合

    一.首先说headless Service和普通Service的区别 headless不分配clusterIP headless service可以通过解析service的DNS,返回所有Pod的地址 ...

  10. ajax+vue简单使用

    <script type="text/javascript" src="http://cdn.bootcss.com/vue/2.2.2/vue.min.js&qu ...