coding++:java-全局异常处理
本次使用工具:SpringBoot <version>1.5.19.RELEASE</version>
Code:

AbstractException:
package mlq.global.anomaly.exception;
import mlq.global.anomaly.utils.ErrorPrintUtils;
public abstract class AbstractException extends RuntimeException {
private static final long serialVersionUID = -5992753399315247713L;
private String errorCode;
private String errorMsg;
private String stackTraceMsg;
private String level;
private String messageID;
private boolean sendMsg = true;
public AbstractException(String code, String message, String... level) {
super(code + "|" + message);
this.handleExceptionMessage(code, message, code + "|" + message);
}
public AbstractException(String code, String message, Throwable th) {
super(code + "|" + message, th);
this.handleExceptionMessage(code, message, ErrorPrintUtils.printStackTrace(th));
}
public final void handleExceptionMessage(String code, String message, String stackTraceMsg) {
this.errorCode = code;
this.errorMsg = message;
this.stackTraceMsg = stackTraceMsg;
}
public AbstractException(Throwable cause) {
super(cause);
ErrorDesc errorDesc = this.getErrorDesc(cause);
if (errorDesc != null) {
this.errorCode = errorDesc.errorCode;
this.errorMsg = errorDesc.errorMsg;
}
}
public AbstractException(String message) {
super(message);
}
public abstract ErrorDesc getErrorDesc(Throwable var1);
public String getErrorCode() {
return this.errorCode;
}
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getStackTraceMsg() {
return this.stackTraceMsg;
}
public void setStackTraceMsg(String stackTraceMsg) {
this.stackTraceMsg = stackTraceMsg;
}
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
public String getMessageID() {
return this.messageID;
}
public void setMessageID(String messageID) {
this.messageID = messageID;
}
public boolean isSendMsg() {
return this.sendMsg;
}
public void setSendMsg(boolean sendMsg) {
this.sendMsg = sendMsg;
}
public static class ErrorDesc {
public String errorCode;
public String errorMsg;
public ErrorDesc(String errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
}
AbstractException
NoveControllerException:
package mlq.global.anomaly.exception;
public class NoveControllerException extends AbstractException {
private static final long serialVersionUID = 8307533385237791476L;
public NoveControllerException(String code, String message) {
super(code, message, new String[0]);
}
public NoveControllerException(String code, String message, Throwable th) {
super(code, message, th);
}
public AbstractException.ErrorDesc getErrorDesc(Throwable var1) {
return null;
}
}
NoveControllerException
CustomException:
package mlq.global.anomaly.exception; /**
* 自定义 异常类
*/
public class CustomException extends NoveControllerException { private static final long serialVersionUID = 1L; public CustomException(String code, String message) {
super(code, message);
} public CustomException(String code, String message, Throwable th) {
super(code, message, th);
} }
CustomException
JsonException:
package mlq.global.anomaly.exception; /**
* 自定义 JsonException
*/
public class JsonException extends NoveControllerException { private static final long serialVersionUID = -5605565877150120787L; public JsonException(String code, String message) {
super(code, message);
} public JsonException(String code, String message, Throwable th) {
super(code, message, th);
} }
JsonException
ErrorPrintUtils:
package mlq.global.anomaly.utils; import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter; public class ErrorPrintUtils { public ErrorPrintUtils() {
} public static String printStackTrace(Throwable exception) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
exception.printStackTrace(pw);
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException var8) {
;
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
}
ErrorPrintUtils
GlobalExceptionHandler:
package mlq.global.anomaly.exception; import com.alibaba.fastjson.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
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.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; /**
* 全局异常类
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
LOGGER.info("Exception异常");
LOGGER.info("RequestURL:url={}", request.getRequestURL());
LOGGER.error("请求地址:url={},系统异常:error={}", request.getRequestURL(), e);
if (!checkAjaxRequest(request)) {
ModelAndView mav = new ModelAndView("500");
mav.addObject("exception", e);
mav.addObject("reqUrl", request.getRequestURL());
return mav;
} else {
ModelAndView mv = new ModelAndView();
// 设置状态码
response.setStatus(HttpStatus.OK.value());
// 设置ContentType
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
// 设置编码格式 避免乱码
response.setCharacterEncoding("UTF-8");
// 头部响应信息
response.setHeader("Cache-Control", "no-cache, must-revalidate");
// 返回结果
response.getWriter().write("{\"resultCode\":500,\"message\":\"" + e.getMessage() + "\"}");
return mv;
}
} /**
* 自定义异常
*
* @throws Exception
*/
@ExceptionHandler(value = CustomException.class)
public ModelAndView callCenterHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
LOGGER.info("自定义异常");
LOGGER.info("RequestURL:url={}", req.getRequestURL());
LOGGER.error("请求地址:url={},CallCenterException异常:error={}", req.getRequestURL(), e);
if (!checkAjaxRequest(req)) {
ModelAndView mav = new ModelAndView("500");
mav.addObject("exception", e.getMessage());
mav.addObject("reqUrl", req.getRequestURL());
return mav;
} else {
ModelAndView mv = new ModelAndView();
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
response.getWriter().write("{\"resultCode\":500,\"message\":\"" + e.getMessage() + "\"}");
return mv;
}
} @ExceptionHandler(value = JsonException.class)
@ResponseBody
public Map<String, Object> jsonErrorHandler(HttpServletRequest req, JsonException e) throws Exception {
LOGGER.info("JSON异常");
LOGGER.info("RequestURL={}", req.getRequestURL());
LOGGER.error("请求地址:url={},ajax请求异常:error={}", req.getRequestURL(), e);
Map<String, Object> map = Collections.synchronizedMap(new HashMap<String, Object>());
map.put("resultCode", 500);
map.put("message", e.getMessage());
return map;
} /**
* 判断是否ajax请求
*
* @param request
* @return
*/
private boolean checkAjaxRequest(HttpServletRequest request) {
String requestType = request.getHeader("X-Requested-With");
if (!ObjectUtils.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) {
return true;
}
return false;
}
}
GlobalExceptionHandler
提示:在没有异常自行处理的时候 就会走全局异常类
coding++:java-全局异常处理的更多相关文章
- Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。
通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法: controller中加入@Valid注解: @Req ...
- Spring Boot 2.x 系列教程:WebFlux REST API 全局异常处理 Error Handling
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 本文内容 为什么要全局异常处理? WebFlux REST 全 ...
- Java开发知识之Java的异常处理
Java开发知识之Java的异常处理 一丶异常概述 在讲解异常之前,我们要搞清楚.什么是异常. 通俗理解就是我们编写的程序出问题了.进行处理的一种手段. 比如我们的QQ.有的时候就崩溃了.比如出现xx ...
- 异常处理器详解 Java多线程异常处理机制 多线程中篇(四)
在Thread中有异常处理器相关的方法 在ThreadGroup中也有相关的异常处理方法 示例 未检查异常 对于未检查异常,将会直接宕掉,主线程则继续运行,程序会继续运行 在主线程中能不能捕获呢? 我 ...
- SpringMVC 全局异常处理
在 JavaEE 项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理.每个过程都单独处理异常,系统的代码耦合度 ...
- SpringBoot整合全局异常处理&SpringBoot整合定时任务Task&SpringBoot整合异步任务
============整合全局异常=========== 1.整合web访问的全局异常 如果不做全局异常处理直接访问如果报错,页面会报错500错误,对于界面的显示非常不友好,因此需要做处理. 全局异 ...
- springBoot注解大全JPA注解springMVC相关注解全局异常处理
https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...
- SpringBoot2 全局异常处理
参考这篇文章里面的几种异常形式: 全局异常处理是个比较重要的功能,一般在项目里都会用到. 大概把一次请求分成三个阶段,来分别进行全局的异常处理. 一:在进入Controller之前,譬如请求一个不存在 ...
- 014-Spring Boot web【三】拦截器HandlerInterceptor、异常处理页面,全局异常处理ControllerAdvice
一.拦截器HandlerInterceptor 1.1.HandlerInterceptor接口说明 preHandle,congtroller执行前,如果返回false请求终端 postHandle ...
- springboot中 简单的SpringMvc全局异常处理
1.全局异常处理类:GlobalExceptionHandler.java package com.lf.exception; import java.util.HashMap; import jav ...
随机推荐
- Object-C 银行卡,信用卡校验规则(Luhn算法)
最近的项目中涉及到绑定用户的银行卡,借记卡.经过查找银行卡的校验规是采用 Luhn算法进行验证. Luhn算法,也被称作“模10算法”.它是一种简单的校验公式,一般会被用于身份证号码,IMEI号码,美 ...
- java基础进阶篇(四)_HashMap------【java源码栈】
目录 一.前言 二.特点和常见问题 二.接口定义 三.初始化构造函数 四.HashMap内部结构 五.HashMap的存储分析 六.HashMap的读取分析 七.常用方法 八.HashMap 的jav ...
- 前阿里数据库专家总结的MySQL里的各种锁(下篇)
在上篇中,我们介绍了MySQL中的全局锁和表锁. 今天,我们专注于介绍一下行锁,这个在日常开发和面试中常常困扰我们的问题. 1.行锁基础 由于全局锁和表锁对增删改查的性能都会有较大影响,所以,我们自然 ...
- 7-8 jmu-python-从列表中删除元素 (15 分)
删除列表中所有符合条件的值. 输入格式: 输入n,代表要测试n次.每次测试:首先,输入1行字符串(字符串内的元素使用空格分隔)然后,输入要删除的元素x. 输出格式: 输出删除元素x后的每行字符串.如果 ...
- 题解-[HNOI2001]遥控赛车比赛
题解-[HNOI2001]遥控赛车比赛 前置知识:记忆化搜索.\(\texttt{Bfs}\). 参考资料 https://www.luogu.com.cn/blog/CYJian/solution- ...
- docker 学习路线
docker 学习路线 参考资料 知乎 docker 的学习路线 Docker - 从入门到实践 Docker 核心技术与实现原理 Docker 入门 <Kubernetes in Action ...
- MyBatis 源码分析-项目总览
MyBatis 源码分析-项目总览 1.概述 本文主要大致介绍一下MyBatis的项目结构.引用参考资料<MyBatis技术内幕> 此外,https://mybatis.org/mybat ...
- Python线性优化基础讲解~
目前,各组织正在利用数据科学和机器学习来解决各种业务问题.为了创造一个真正的业务影响,如何弥合数据科学管道和业务决策管道之间的差距显得尤为重要. 数据科学管道的结果往往是数据中的预测.模式和洞察(通常 ...
- 如何在PHP7中扩展mysql,先安装php7.2。后安装mysql
相对与PHP5,PHP7的最大变化之一是移除了mysql扩展,推荐使用mysqli或者pdo_mysql,实际上在PHP5.5开始,PHP就着手开始准备弃用mysql扩展,如果你使用mysql扩展,可 ...
- Spark实战--寻找5亿次访问中,访问次数最多的人
问题描述 对于一个大型网站,用户访问量尝尝高达数十亿.对于数十亿是一个什么样的概念,我们这里可以简单的计算一下.对于一个用户,单次访问,我们通常会记录下哪些数据呢? 1.用户的id 2.用户访问的时间 ...