统一异常处理:

@ControllerAdvice
public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(getClass()); /**
* 处理自定义异常
*/
@ExceptionHandler(AuthException.class)
@ResponseBody
public R handleRRException(AuthException e){
R r = new R();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
} @ExceptionHandler(Exception.class)
@ResponseBody
public R handleException(Exception e) {
logger.error(e.getMessage(), e);
return R.error();
}
}

现在网上一般都是这种比较简单的写法

还有其他方式:

public class ControllerExceptionResolver extends ExceptionHandlerExceptionResolver {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionResolver.class);

    protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
String uri = request.getRequestURI();
LOG.error("异常url:" + uri + ",处理框架", exception);
if (exception instanceof StoneSystemRuntimeException) {
// TODO 攻击或被异常访问才会出现
StoneSystemRuntimeException stoneRuntimeException = (StoneSystemRuntimeException) exception;
BasicRes res = new BasicRes();
res.setMsg(stoneRuntimeException.getMsg());
res.setResCode(stoneRuntimeException.getCode());
this.excuteJson(response, res);
LOG.error("系统运行时异常", exception);
} else if (exception instanceof StoneBizzRuntimeException) {
// TODO 普通业务异常
StoneBizzRuntimeException stoneBizzException = (StoneBizzRuntimeException) exception;
BasicRes res = new BasicRes();
res.setMsg(stoneBizzException.getMsg());
res.setResCode(stoneBizzException.getCode());
this.excuteJson(response, res);
LOG.error("业务异常", exception);
} else {
// TODO 其他未处理异常
BasicRes res = new BasicRes();
res.setMsg("系统更新中,请稍后再试");
res.setResCode(ErrorCode.SYSTEM_EXCEPTION.getCode());
this.excuteJson(response, res);
LOG.error("未定义异常", exception);
}
return new ModelAndView(); } private String excuteJson(HttpServletResponse response, BasicRes res) {
try {
byte[] jsonBytes = JSON.toJSONBytes(res);
String exJson = new String(jsonBytes, SysConstant.CHARSET_UTF8);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(exJson);
return exJson;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
} }

替换默认:

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter { @Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
super.extendHandlerExceptionResolvers(exceptionResolvers);
exceptionResolvers.add(this.getControllerExceptionResolver());
} @Bean
public ControllerExceptionResolver getControllerExceptionResolver() {
return new ControllerExceptionResolver();
}
}

继承实现ExceptionHandlerExceptionResolver类,这个类一般多见在SpringMVC中,但是SpringBoot中也可以继续使用

http://blog.didispace.com/springbootexception/

http://www.cnblogs.com/xinzhao/p/4902295.html

https://juejin.im/entry/5a5f3d61f265da3e5537f113

SpringBoot 统一异常处理的更多相关文章

  1. spring 或 springboot统一异常处理

    spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义 ...

  2. SpringBoot统一异常处理后TX-LCN分布式事务无法捕获异常进行回滚

    通常我们使用SpringBoot都会进行统一异常处理,例如写一个BaseController,在BaseController里进行统一异常处理,然后其他的Controller都继承BaseContro ...

  3. springboot统一异常处理类及注解参数为数组的写法

    统一异常处理类 package com.wdcloud.categoryserver.common.exception; import com.wdcloud.categoryserver.commo ...

  4. springboot统一异常处理及返回数据的处理

    一.返回code数据的处理 代码: Result.java /** * http请求返回的最外层对象 * Created by 廖师兄 * 2017-01-21 13:34 */ public cla ...

  5. SpringBoot统一异常处理

    /** * 异常处理器 */ @RestControllerAdvice // public class BDExceptionHandler { private Logger logger = Lo ...

  6. Springboot统一异常处理(@ControllerAdvice)

    import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind ...

  7. 【异常处理】Springboot对Controller层方法进行统一异常处理

    Controller层方法,进行统一异常处理 提供两种不同的方案,如下: 方案1:使用 @@ControllerAdvice (或@RestControllerAdvice), @ExceptionH ...

  8. 配置springboot在访问404时自定义返回结果以及统一异常处理

    在搭建项目框架的时候用的是springboot,想统一处理异常,但是发现404的错误总是捕捉不到,总是返回的是springBoot自带的错误结果信息. 如下是springBoot自带的错误结果信息: ...

  9. springboot返回统一接口与统一异常处理

    springboot返回统一接口与统一异常处理 编写人员:yls 编写时间:2019-9-19 0001-springboot返回统一接口与统一异常处理 简介 创建统一的返回格式 Result 封装统 ...

随机推荐

  1. Android -- 实现RecyclerView可拖拽Item

    1,今天和大家一起实现RecyclerView可拖拽Item,主要是使用RecyclerView结合ItemTouchHelper来实现的,来看一下效果 2,看一下怎么实现的呢,很简单,只需要给rec ...

  2. c#之如何正确地实现IDisposable接口

    见实例: public class TestClass : IDisposable { //供程序员显式调用的Dispose方法 public void Dispose() { //调用带参数的Dis ...

  3. kail linux arp欺骗

    首先连接wifi,进入内网 1,查看内网的存活主机  命令  fping -asg 192.168.1.0/24    (视不同环境而定,假设这里的路由器地址为 192.168.1.1) 也可利用其他 ...

  4. JavaScript中直接量和变量

    标题 1.直接量 顾名思义,可以直接拿来使用的量.那哪些是直接量呢?数据类型又有很多种,因为不同类型的数据处理方式是不同的,所以数据要分类型 基本类型 1.1 String字符串 用单引号或双引号引起 ...

  5. Python -- print(dataframe)时,省略部分列。

    import pandas as pd # 导入后加入以下列,再显示时显示完全. pd.set_option('display.max_rows',500) pd.set_option('displa ...

  6. Web API 跨域请求

    分布式技术在项目中会频繁用到,以前接触过WebService(可跨平台).WCF(功能强大,配置繁琐),    最近由于上层业务调整,将原来的MVC项目一分为三,将数据层提取出来,用API去访问.然后 ...

  7. Spark学习之路 (八)SparkCore的调优之开发调优

    摘抄自:https://tech.meituan.com/spark-tuning-basic.html 前言 在大数据计算领域,Spark已经成为了越来越流行.越来越受欢迎的计算平台之一.Spark ...

  8. STL容器之deque

    [1]deque容器 deque 是对 vector 和 list 优缺点的结合,它是处于两者之间的一种容器. [2]deque方法集 应用示例代码: #include <deque> # ...

  9. MongoDB-Java的两个基本操作Upsert和insertMany

    此文只是为了记录几个基本操作,首先Upsert,有多种方法可以进行,但是都需要指定UpdateOptions.upsert(true),其中最简单的办法如下(eqq是一个用来filter的BSON,具 ...

  10. Vue.js是什么,vue介绍

    Vue.js是什么,vue介绍 Vue.js 是什么Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架.与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用. ...