一、全局异常处理

//Result定义全局数据返回对象
package com.xiaobing.demo001.domain; public class Result {
private Integer code;
private String message;
private Object data; public Integer getCode() {
return code;
} public String getMessage() {
return message;
} public Object getData() {
return data;
} public void setCode(Integer code) {
this.code = code;
} public void setMessage(String message) {
this.message = message;
} public void setData(Object data) {
this.data = data;
} public Result() {
} public Result(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
} @Override
public String toString() {
return "Result{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}

(1) RestControllerAdvice注解使用,如下全局异常示例:
注解: @RestControllerAdvice 和@ControllerAdvice 是用来修饰类的,表示为一个增强类…我们定义全局异常拦截通常是使用 @RestControllerAdvice结合 @ExceptionHandler 来捕获绝大部分异常,然后统一返回Json形式…

//假如当传参为0 时肯定会报错 除数不能为0
package com.xiaobing.demo001.controller; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("api/v1/test")
public class TestExceptionController { @GetMapping("abnormal")
public void testExt() {
int i = 1/0;
}
}
//全局异常捕获方法
package com.xiaobing.demo001.handler; import com.xiaobing.demo001.domain.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest; /**异常处理类
* @author Administrator
*/
@RestControllerAdvice
public class ExceptionsHandler { @ExceptionHandler(value = Exception.class)
Result handlerException(Exception e, HttpServletRequest request) { return new Result(500,"服务器异常","");
}
}

二、针对性异常捕获

@ExceptionHandler(value = ArithmeticException.class)
Result arithmeticExceptionException(ArithmeticException e, HttpServletRequest request) { return new Result(-1,"除数不能为0","");
}

三、自定义异常捕获

//自定义异常类
package com.xiaobing.demo001.domain; public class MyException extends RuntimeException { private String code;
private String 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;
} public MyException() {
} public MyException(String msg) {this.msg = msg;
}
}
//业务代码,MyException
@RestController
@RequestMapping("api/v1/test")
public class TestExceptionController {
@GetMapping("myException")
public void testMyExcsption() {
throw new MyException("自定义异常信息");
}
//捕获我们新增的异常
@ExceptionHandler(value = MyException.class)
Result myException(MyException e, HttpServletRequest request) {
return new Result(-1,"自定义异常信息","");
}

四、常用异常捕获分享

    /** 运行时异常 */
@ExceptionHandler(RuntimeException.class)
public Result runtimeExceptionHandler(RuntimeException ex) {
return Result.error("运行时异常");
} /** 空指针异常 */
@ExceptionHandler(NullPointerException.class)
public Result nullPointerExceptionHandler(NullPointerException ex) {
return Result.error("空指针异常");
} /** 类型转换异常 */
@ExceptionHandler(ClassCastException.class)
public Result classCastExceptionHandler(ClassCastException ex) {
return Result.error("类型转换异常");
}
/** 文件未找到异常 */
@ExceptionHandler(FileNotFoundException.class)
public Result FileNotFoundException(FileNotFoundException ex) {
return Result.error("文件未找到异常");
}
/** 数字格式异常 */
@ExceptionHandler(NumberFormatException.class)
public Result NumberFormatException(NumberFormatException ex) {
return Result.error("数字格式异常");
}
/** 安全异常 */
@ExceptionHandler(SecurityException.class)
public Result SecurityException(SecurityException ex) {
return Result.error("安全异常");
}
/** sql异常 */
@ExceptionHandler(SQLException.class)
public Result SQLException(SQLException ex) {
return Result.error("sql异常");
}
/** 类型不存在异常 */
@ExceptionHandler(TypeNotPresentException.class)
public Result TypeNotPresentException(TypeNotPresentException ex) {
return Result.error("类型不存在异常");
} /** IO异常 */
@ExceptionHandler(IOException.class)
public Result iOExceptionHandler(IOException ex) {
log.error("IO异常:{} ", ex.getMessage(), ex);
return Result.error("IO异常");
} /** 未知方法异常 */
@ExceptionHandler(NoSuchMethodException.class)
public Result noSuchMethodExceptionHandler(NoSuchMethodException ex) {
log.error("未知方法异常:{} ", ex.getMessage(), ex);
return Result.error("未知方法异常");
} /** 数组越界异常 */
@ExceptionHandler(IndexOutOfBoundsException.class)
public Result indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
return Result.error("数组越界异常");
}
/** sql语法错误异常 */
@ExceptionHandler(BadSqlGrammarException.class)
public Result BadSqlGrammarException(BadSqlGrammarException ex) {
return Result.error("sql语法错误异常");
} /** 无法注入bean异常 */
@ExceptionHandler(NoSuchBeanDefinitionException.class)
public Result NoSuchBeanDefinitionException(NoSuchBeanDefinitionException ex) {
return Result.error("无法注入bean");
} /** Http消息不可读异常 */
@ExceptionHandler({HttpMessageNotReadableException.class})
public Result requestNotReadable(HttpMessageNotReadableException ex) {
return Result.error("Http消息不可读");
} /** 400错误 */
@ExceptionHandler({TypeMismatchException.class})
public Result requestTypeMismatch(TypeMismatchException ex) {
return Result.error("服务器异常");
} /** 500错误 */
@ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
public Result server500(RuntimeException ex) {
return Result.error("服务器异常");
} /** 栈溢出 */
@ExceptionHandler({StackOverflowError.class})
public Result requestStackOverflow(StackOverflowError ex) {
return Result.error("栈溢出异常");
} /** 除数不能为0 */
@ExceptionHandler({ArithmeticException.class})
public Result arithmeticException(ArithmeticException ex) {
return Result.error("除数不能为0异常");
} /** 其他错误 */
@ExceptionHandler({Exception.class})
public Result exception(Exception ex) {
return Result.error("网络连接失败,请退出后再试");
}

SpringBoot 全局异常拦截捕获处理的更多相关文章

  1. SpringBoot全局异常拦截

    SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...

  2. springboot全局异常拦截源码解读

    在springboot中我们可以通过注解@ControllerAdvice来声明一个异常拦截类,通过@ExceptionHandler获取拦截类抛出来的具体异常类,我们可以通过阅读源码并debug去解 ...

  3. SpringBoot全局异常的捕获设置

    1.新建立一个捕获异常的实体类 如:LeeExceptionHandler package com.leecx.exception; import javax.servlet.http.HttpSer ...

  4. Asp.Netcore使用Filter来实现接口的全局异常拦截,以及前置拦截和后置拦截

    原文链接:https://blog.csdn.net/qq_38762313/article/details/85234594 全局异常拦截器:       解决写每个接口都需要去做容错而添加try{ ...

  5. Spring 全局异常拦截根据业务返回不同格式数据 自定义异常

    1.全局异常拦截:针对所有异常进行拦截 可根据请求自定义返回格式 2.自定义异常类 处理不同业务的异常 接下来开始入手代码: 1).自定义异常类 @ControllerAdvice//添加注解 记得开 ...

  6. springboot 全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  7. python中如何用sys.excepthook来对全局异常进行捕获、显示及输出到error日志中

    使用sys.excepthook函数进行全局异常的获取. 1. 使用MessageDialog实现异常显示: 2. 使用logger把捕获的异常信息输出到日志中: 步骤:定义异常处理函数, 并使用该函 ...

  8. springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler

    前言 本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用 ...

  9. 爱上MVC~业务层刻意抛出异常,全局异常的捕获它并按格式返回

    回到目录 对于业务层的程序的致命错误,我们一直的做法就是直接抛出指定的异常,让程序去终断,这种做法是对的,因为如果一个业务出现了致命的阻塞的问题,就没有必要再向上一层一层的返回了,但这时有个问题,直接 ...

随机推荐

  1. Jmeter扩展组件开发(10) - 自定义扩展函数助手的开发

    CODE package com.functions;import org.apache.jmeter.engine.util.CompoundVariable;import org.apache.j ...

  2. Spring Security 学习+实践

    Spring Security是Spring为解决应用安全所提供的一个全面的安全性解决方案.基于Spring AOP和Servlet过滤器,启动时在Spring上下文中注入了一组安全应用的Bean,并 ...

  3. 这两个基础seo插件,wordpress网站必装

    WordPress对搜索引擎非常友好,这一点很多人都知道.不过我们在制作完成WordPress主题后,还可以在原来的良好基础上,添加两个队seo非常有利的WordPress插件. 第一个插件:Baid ...

  4. Interrupted Exception异常可能没你想的那么简单!

    摘要: 当我们在调用Java对象的wait()方法或者线程的sleep()方法时,需要捕获并处理InterruptedException异常.如果我们对InterruptedException异常处理 ...

  5. canvas 实现简单的画板功能添加手机端效果 1.01

    在上次的基础上,加了一些代码,手机端可操作 访问网址:https://chandler712.github.io/Item/ <!-- 简单版画板 --> <!DOCTYPE htm ...

  6. Midway Serverless 发布 2.0,一体化让前端研发再次提效

    作者 | 张挺 来源 | Serverless 公众号 自去年 Midway Serverless 1.0 发布之后,许多业务开始尝试其中,并利用 Serverless 容器的弹性能力,减少了大量研发 ...

  7. transformers---BERT

    transformers---BERT BERT模型主要包括两个部分,encoder和decoder,encoder可以理解为一个加强版的word2vec模型,以下是对于encoder部分的内容 预训 ...

  8. 前段之jQuery

    一.jQuery介绍 jQuery是一个轻量级的.兼容多浏览器的JavaScript库. jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方便地进行Ajax交 ...

  9. 基于BootStrap的轮播图

    准备 先设计一个承载轮播图的区域:四周向外阴影.扁平圆角: 1 #myShuffArea{ 2 width: 50%; 3 height: 300px; 4 border: solid 1px gai ...

  10. Apache Beam入门及Java SDK开发初体验

    1 什么是Apache Beam Apache Beam是一个开源的统一的大数据编程模型,它本身并不提供执行引擎,而是支持各种平台如GCP Dataflow.Spark.Flink等.通过Apache ...