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 ... 
随机推荐
- 启动时查看配置文件application.yml
			Spring Boot Application 事件和监听器 在多环境的情况下. 可能需要切换配置文件的一个对应的属性来切换环境 面临的问题就是 如何在springboot加载完配置文件的时候就可以立 ... 
- [红日安全]Web安全Day5 - 任意文件上传实战攻防
			本文由红日安全成员: MisakiKata 编写,如有不当,还望斧正. 大家好,我们是红日安全-Web安全攻防小组.此项目是关于Web安全的系列文章分享,还包含一个HTB靶场供大家练习,我们给这个项目 ... 
- iMX287A多种方法实现流水灯效果
			目录 1.流水灯在电子电路中的地位 2.硬件电路分析 3.先点个灯吧 4.shell脚本实现流水灯 5.ANSI C文件操作实现流水灯 6.Linux 系统调用实现流水灯 @ 1.流水灯在电子电路中的 ... 
- SpringBoot入门系列(三)资源文件属性配置
			前面介绍了Spring的@Controller和@RestController控制器, 他们是如何响应客户端请求,如何返回json数据.不清楚的朋友可以看看之前的文章:https://www.cnbl ... 
- 关于IT培训机构的个人看法
			1.前言 缘分与巧合,最近接触比较多的培训机构出来的人,以及看过关于培训机构的文章和问答.虽然没在培训机构上过课,但是接触过很多培训机构出来的人,也看过一些培训机构的课程.关于培训机构,我也有自己的看 ... 
- vue项目用sha256、md5、base64加密密码
			无论你开发什么样的项目,你可能都会要开发登录.注册.修改密码.忘记密码这些功能,少数项目除外!!要实现这些功能,对于保护用户或者管理员账号密码,这是我们程序员肯定要做的事情.要是用户密码不加密,用明文 ... 
- IntelliJ IDEA神器使用技巧
			说明:详情请参考慕课网课程:IntelliJ IDEA神器使用技巧:http://www.imooc.com/learn/924(感谢课程作者:闪电侠) 推荐: 1. 课程老师(闪电侠)IDEA快捷键 ... 
- Vue Snackbar 消息条队列显示,依次动画消失的实现
			效果预览 思路 封装 Snackbar 组件: 在根路由页面下建立全局 Snackbar 控制器,统一管理 Snackbar: 通过事件通知全局 Snackbar 控制器显示消息: 实现 1. 封装 ... 
- Go语言转义字符
			\a 匹配响铃符 (相当于 \x07) 注意:正则表达式中不能使用 \b 匹配退格符,因为 \b 被用来匹配单词边界, 可以使用 \x08 表示退格符. \f 匹配换页符 (相当于 \x0C) \t ... 
- linux中的源码安装
			前两天自己在笔记本上装了CentOs版本的虚拟机,接着要装Python3,是源码安装的挺费劲,个人总结了一些源码安装的经验,今天在这里给大家分享一下. 1. 首先准备环境,安装必要的编译工具gcc g ... 
