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 ...
随机推荐
- jq拖拽插件
(function ($) { var move = false; //标记控件是否处于被拖动状态 var dragOffsetX = 0; //控件左边界和鼠标X轴的差 var dragOffset ...
- HTTP协议 有这篇文章足够了
HTTP 协议详解 HTTP(HyperText Transfer Protocol)超文本传输协议.其最初的设计目的是为了提供一种发布和接收HTML页面的方法. HTTP是一个客户端(用户)和服务端 ...
- Taro_Mall 是一款多端开源在线商城小程序.
介绍 Taro_Mall是一款多端开源在线商城应用程序,后台是基于litemall基础上进行开发,前端采用Taro框架编写,现已全部完成小程序和h5移动端,后续会对APP,淘宝,头条,百度小程序进行适 ...
- 基于JS正则实现模板数据动态渲染
最近业务上需要动态渲染模板数据: 一.业务需求: 1.前端后端定义好模板以及变量名,根据打印机类型转换成对应sdk需要的标签模板,保存数据库 2.订单数据是前端根据支付结果获取的,最终渲染完的数据模板 ...
- 【每日一包0018】fecha
[github地址:https://github.com/ABCDdouyae...] fecha 比moment.js更加轻量级的时间解析和格式化包 format 用法:format(<Dat ...
- 纯CSS实现带返回顶部右侧悬浮菜单
这是我做个人网页的时候加上的带返回顶部右侧悬浮菜单效果,如下图, 使用工具是Hbuilder. 代码如下: <!DOCTYPE html> <html> <head> ...
- 峰哥说技术:09-Spring Boot整合JSP视图
Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 09 峰哥说技术:Spring Boot整合JSP视图 一般来说我们很少推荐大家在Spring boot ...
- 微服务架构-Gradle下载安装配置教程
一.开发条件 JDK8下载地址:https://www.oracle.com/java/technologies/javase-jdk8-downloads.html Eclipse下载地址:http ...
- python自动化第一课 - python安装以及pycharm配置
1.安装python 1.1打开python官网https://www.python.org/downloads/windows/进行下载Python 3.8.0 1.2下载完毕后进行安装,1勾选 A ...
- ggplot2(3) 语法突破
3.1 简介 图形图层语法基于Wilkinson的图形语法,并在其基础上添加了许多新功能,使得图形更有表现力,并能完美地嵌入到R的环境中. 图形图层语法使得图形的重复更新变得简单——每次只更新一个特征 ...