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 ...
随机推荐
- xshell6使用的命令
我们进入Xshell的界面之后连接上Linux服务器 常用命令: (1)命令ls——列出文件 ls -la 给出当前目录下所有文件的一个长列表,包括以句点开头的“隐藏”文件 ls a* 列出当前目录下 ...
- python库常用函数学习
os.path #返回标准化的绝对路径,基本等同于normpath() os.path.abspath(path) #返回文件名 os.path.basename(path) #返回目录名 os.pa ...
- ASP.NET CORE 内置的IOC解读及使用
在我接触IOC和DI 概念的时候是在2016年有幸倒腾Java的时候第一次接触,当时对这两个概念很是模糊:后来由于各种原因又回到.net 大本营,又再次接触了IOC和DI,也算终于搞清楚了IOC和DI ...
- @JsonFormat、@DateTimeFormat注解,读取数据库晚一天问题
@DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss&qu ...
- 峰哥说技术:01-Spring Boot介绍
Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 Spring Boot介绍 A.Spring Boot是什么? 由于Spring是一个轻量级的企业开发框架 ...
- html标签及网页语义化理解
最近重新看了一遍html标签的知识,有很多新的体会,对语义化有了一个新的理解. 那么什么叫做语义化呢,说的通俗点就是:明白每个标签的用途(在什么情况下使用此标签合理)比如,网页上的文章的标题就可以用标 ...
- ggplot2(10) 减少重复性工作
10.1 简介 灵活性和鲁棒性的敌人是:重复! 10.2 迭代 last_plot()用于获取最后一次绘制或修改的图形. 10.3 绘图模板 gradient_rb <- scale_colou ...
- 上海月薪 1w 和家乡月薪 5000 你选择哪?
如题,这是我在知乎上看到的一个热门话题--要现在的我来回答的话,毫无疑问会选择上海,即便月薪只有 5000 也去,还要趁早去. 有读者可能会质问我:"你之前不是说在三线城市洛阳工作很爽吗?怎 ...
- css3特性简要概括
---恢复内容开始--- css3新增核心知识 背景和边框 文本效果 2d/3d转换 过渡和动画 多列布局 弹性盒模型 媒体查询 增强选择器 css3浏览器兼容性 css3在线工具 css3gener ...
- Ubuntu下实现歌词解析
我们要明确目的,实现歌曲歌词同步. 1.将歌词文件一次性去取到内存中.(以周董的“简单爱”为例) a.用fopen打开歌词文件 FILE *fp = fopen(“简单爱.lrc”,"r& ...