java controller 异常捕获
package com.aiyusheng.framework.exception; import lombok.Data; /**
* base异常类
* @author :cza
* @date :2020/11/25 15:57
* @description :
* @modyified By:
*/
@Data
public class BaseException extends Exception {
private String code; public BaseException(Throwable throwable){
super(throwable);
}
public BaseException(String msg){
super(msg);
}
public BaseException(String msg,Throwable throwable){
super(msg,throwable);
} @Deprecated
public BaseException(Throwable throwable,String msg,String code){
super(msg,throwable);
this.code=code;
}
}
package com.aiyusheng.framework.exception; import com.aiyusheng.framework.core.enums.ReturnCode;
import com.aiyusheng.framework.utils.CommUtil;
import lombok.Data; import javax.swing.plaf.PanelUI;
import java.io.Serializable; /**
* 业务异常类
* @author :cza
* @date :2020/11/25 15:57
* @description :
* @modyified By:
*/ public class BusinessException extends BaseException implements Serializable { private static final long serialVersionUID = -3598204678161713009L; /**
* 结果码
*/
private String code; /**
* 提示消息
*/
private String msg;
/**
* 提示消息,用于填充properties中的{}参数
*/
private String [] msgParams; /**
* 功能描述:不带信息参数的异常<br>
* @Param code
* @Param throwable
* @Return
* @Author: cza
* @Date: 2020-11-26
* */
public BusinessException(String code,Throwable throwable){
super(CommUtil.getResultMsg(code,null),throwable);
this.code=code;
this.setCode(code);
} /**
* 功能描述:不带信息参数的异常<br>
* @Param code
* @Param throwable
* @Return
* @Author: cza
* @Date: 2020-11-26
* */
public BusinessException(ReturnCode returnCode){
super(returnCode.getMsg());
this.setCode(returnCode.getCode());
} public BusinessException(ReturnCode returnCode,String [] msgParams,Throwable throwable){
super(CommUtil.getResultMsg(returnCode.getMsg(),msgParams),throwable);
this.code=returnCode.getCode();
//不直接传递引用是处于代码安全考虑,避免位置调用者修改引用内容
this.msgParams=msgParams.clone();
this.setCode(returnCode.getCode());
} /**
* 功能描述:带一个信息参数的异常
* @Param:
* @Return
* @Author: chenzhian
* @Date:2020-11-26
*/
public BusinessException(String code,String msgParam,Throwable throwable){
super(CommUtil.getResultMsg(code, new String [] {msgParam}),throwable);
this.code=code;
//不直接传递引用是处于代码安全考虑,避免位置调用者修改引用内容
this.msgParams[0]=msgParam;
this.setCode(code);
} /**
* 功能描述: 带多个信息参数的异常
* @Param:
* @param code
* @param msgParams
* @param throwable
* @Return:
* @Author: chenzhian
* @Date: 2020/11/26 15:43
* @Description:
*/
@Deprecated
public BusinessException(String code,String [] msgParams,Throwable throwable) {
super(CommUtil.getResultMsg(code,msgParams),throwable);
this.code=code;
//不直接传递引用是处于代码安全考虑,避免位置调用者修改引用内容
this.msgParams=msgParams.clone();
this.setCode(code);
} /**
* 功能描述: 带多个信息参数的异常
* @Param:
* @param code
* @param throwable
* @param msgParams
* @Return:
* @Author: chenzhian
* @Date: 2020/11/26 15:45
* @Description:
*/
public BusinessException(String code,Throwable throwable,String... msgParams) {
super(CommUtil.getResultMsg(code,msgParams),throwable);
this.code=code;
//不直接传递引用是处于代码安全考虑,避免位置调用者修改引用内容
this.msgParams=msgParams.clone();
this.setCode(code);
} /**
* 功能描述: 异常信息构造函数,用于FA框架反射调用
* @Param:
* @param resultMsg
* @Return:
* @Author: chenzhian
* @Date: 2020/11/26 15:46
* @Description:
*/
public BusinessException(String resultMsg){
super(resultMsg);
} @Override
public String getCode(){
return code;
} @Override
public void setCode(String code){
this.code=code;
} public String [] getMsgParams() {
//不直接返回msgParams引用为了代码安全,避免被未知调用者修改引用的内容
return msgParams.clone();
} public void setMsgParams(String [] msgParams){
//不直接复制msgParams引用为了代码安全,避免被未知调用者修改引用的内容
this.msgParams=msgParams.clone();
} /**
* 功能描述:
* @Param: [returnCode, msgParam, throwable]
* @Return:
* @Author:
* @Date: 2020/11/26 14:37
* @Description:
public BusinessException(ReturnCode returnCode,String msgParam,Throwable throwable){
super(CommUtil.getResultMsg(returnCode.getMsg(), new String [] {msgParam}),throwable);
this.code=returnCode.getCode();
//不直接传递引用是处于代码安全考虑,避免位置调用者修改引用内容
this.msgParams[0]=msgParam;
this.setCode(returnCode.getCode());
}*/
}
package com.aiyusheng.framework.core; import com.aiyusheng.framework.core.enums.ReturnCode;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.shiro.crypto.hash.Hash; import java.io.Serializable;
import java.util.HashMap;
import java.util.Map; /**
* @author :cza
* @date :2020/11/26 20:41
* @description :
* @modyified By:
*/
@Data
@Accessors(chain = true)
public class ResponseResult<T> implements Serializable {
private String code;
private String msg;
private T data; public ResponseResult(){
this(ReturnCode.Common.SUCCESS,null);
}
public ResponseResult(T data){
this(ReturnCode.Common.SUCCESS,data);
}
public ResponseResult(ReturnCode returnCode){
this(returnCode,null);
}
public ResponseResult(ReturnCode returnCode,T data){
//this(returnCode,null);
this.code=returnCode.getCode();
this.msg=returnCode.getMsg();
}
public ResponseResult(String code,String msg){
this.code=code;
this.msg=msg;
this.data=transferNull2EmptyFloag?(T)"":null;
} public ResponseResult(String code,String msg,T data){
this.code=code;
this.msg=msg;
this.data=transNullToEmptyString(data);
} public static <T> ResponseResult<T> success(T data){
return new ResponseResult<>(data);
}
public static <T> ResponseResult<T> success(T data,String message){
return new ResponseResult<>(data).setMsg(message);
}
public static <T> ResponseResult<T> success(){
return new ResponseResult<>();
}
public static <T> ResponseResult<T> error(String errorMsg){
return new ResponseResult<>(ReturnCode.Common.RUNTIME_EXCEPTION.getCode(),errorMsg);
}
public static <T> ResponseResult<T> error(String errorCode,String errorMsg){
return new ResponseResult<>(errorCode,errorMsg);
} /**
* 功能描述:检查是否成功
* @Param:
* @Return: boolean
* @Author: chenzhian
* @Date: 2020/11/27 11:13
* @Description:
*/
public boolean checkResult(){
return ReturnCode.Common.SUCCESS.getCode().equals(code);
}
/**
* 功能描述:复制code和msg信息
* @Param:
* @Return: com.aiyusheng.framework.core.ResponseResult<M>
* @Author: chenzhian
* @Date: 2020/11/27 11:18
* @Description:
*/
public <M> ResponseResult<M> copy(){
return new ResponseResult<>(this.code,this.msg);
}
/**
* 功能描述: 复制code和msg信息,并设置data数据
* @Param:
* @Return: com.aiyusheng.framework.core.ResponseResult<M>
* @Author: chenzhian
* @Date: 2020/11/27 11:18
* @Description:
*/
public <M> ResponseResult<M> copyAndSetData(){
return new ResponseResult<>(this.code,this.msg);
} @Override
public String toString() {
Map<String,Object> jsonMap=new HashMap<>();
jsonMap.put("code",this.code);
jsonMap.put("msg",this.msg);
jsonMap.put("data",transNullToEmptyString(this.data));
return JSONPObject.toJSONString(jsonMap, SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteDateUseDateFormat);
} @Deprecated
private T transNullToEmptyString(T data) {
if(null==data){
return transferNull2EmptyFloag?(T)"":data;
}
return data;
} public static volatile boolean transferNull2EmptyFloag=false;
}
package com.aiyusheng.framework.core.enums; /**
* @author :cza
* @date :2020/11/26 11:15
* @description :
* @modyified By:
*/
public interface ReturnCode {
public String getCode();
public String getMsg();
public String getMsg(String code);
/**
* 功能描述:定义框架级别的编码 <br>
* @Param:
* @Return
* @Author:
* @Date:
*/
public enum Common implements ReturnCode{
/**
成功
*/
SUCCESS("00000","成功"),
/**
服务器繁忙 fixme
*/
BUSINESS_PROCESS_FAILED("950001","服务器繁忙"),
/*
字段校验非法
*/
INVAID_PARAM("940001","字段校验非法"),
/*
运行时异常
*/
INVAID_REQUEST_MSG("940001","运行时异常"),
/*
token 校验不通过
1.1.8 版本之前是非法用户
*/
INVAID_VIRTUAL_USER("940102","非法虚拟用户"),
/*
请求参数错误()
*/
INVAID_REQUEST("940103","请求方式错误"), /*
运行时异常()
*/
RUNTIME_EXCEPTION("950102","运行时异常"), GATE_EXCEPTION("940502","网关繁忙"),
CLIENT_ABORT("950504","请求超时"); private String code;
private String msg;
private Common(String code,String msg){
this.code=code;
this.msg=msg;
} public String getCode() {
return code;
} public String getMsg() {
return msg;
} public String getMsg(String code) {
return msg;
}
}
}
/**
* @author :cza
* @date :2020/11/25 15:56
* @description :
* @modyified By:
*/ import com.aiyusheng.framework.core.ResponseResult;
import com.aiyusheng.framework.core.enums.ReturnCode;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
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.bind.annotation.ResponseStatus; import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays; @ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); public static final String FINAL_MESSAGE="服务器内部错误,请联系系统管理员";
/**
* 功能描述:自定义后的异常处理
* @Param:
* @param ex
* @Return: com.aiyusheng.framework.core.ResponseResult
* @Author: chenzhian
* @Date: 2020/12/3 19:21
* @Description:
*/
@ExceptionHandler(value = BusinessException.class)
public ResponseResult BusinessExceptionHandle(BusinessException ex) {
ex.printStackTrace();
//记录日志
logger.error("\nBusinessExceptionHandle {}", getStackTrace(ex));
String code=ex.getCode();
String message=FINAL_MESSAGE;
if(ex.getMsgParams()!=null&&ex.getMsgParams().length>0){
message= Arrays.toString(ex.getMsgParams());
}
return new ResponseResult(ReturnCode.Common.BUSINESS_PROCESS_FAILED, "服务器内部错误,请联系系统管理员!"); } /** 获取堆栈信息
* 功能描述:
* @Param:
* @param throwable
* @Return: java.lang.Throwable
* @Author: chenzhian
* @Date: 2020/12/3 19:25
* @Description:
*/
private String getStackTrace(Throwable throwable) {
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
} /**
* 功能描述: 统一拦截自定义异常
* @Param:
* @param ex
* @Return: com.aiyusheng.framework.core.ResponseResult
* @Author: chenzhian
* @Date: 2020/12/3 19:21
* @Description:
*/
@ExceptionHandler(value = Exception.class)
public ResponseResult exceptionHandle(Exception ex) {
//根据某个类型进行具体返回
/*
if(e instanceof BadRequestException){
return new ResponseResult(400, e.getMessage());
} if(e instanceof NoAuthorityException){
return new BaseResponse(401, e.getMessage());
} if(e instanceof FailureException){
return new BaseResponse(500, e.getMessage());
} else {//其他未捕获异常
LOGGER.error("exception:{}", e.getMessage(), e);}*/
return new ResponseResult(ReturnCode.Common.BUSINESS_PROCESS_FAILED, "服务器内部错误,请联系系统管理员!"); } /**
* 拦截@RequestBody上validate失败后抛出的异常:MethodArgumentNotValidException
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult parameterExceptionHandler(MethodArgumentNotValidException e) {
logger.error("exception:{}", e.getMessage());
return new ResponseResult(ReturnCode.Common.BUSINESS_PROCESS_FAILED, "服务器内部错误,请联系系统管理员!");
}
}
引用包
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.33</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
</dependencies>
java controller 异常捕获的更多相关文章
- java代码异常捕获throws抛出异常
总结:Throwable 是所以异常的父类.error和Exception是继承它的类 Exception: 这类异常一般是外部错误,例如试图从文件尾后读取数据等,这并不是程序本身的错误,而是在应用环 ...
- java多线程异常捕获
java多线程中出现了异常,如何捕获.利用UncaughtExceptionHandler这个接口就可以了. 代码如下: package com.ming.thread.six.threadcreat ...
- java ThreadPoolExecutor 异常捕获
一,创建一个线程池 其中: public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) 饱和策略执行时的具体逻辑. p ...
- java 异常捕获小记
java 中异常捕获常用的为: try{ //业务代码 }catch(Exception e){ //异常捕获 }finally{ // 不管有无异常, 最后都会执行到这里 } 在方法体内如果想要把异 ...
- [javaSE] 异常捕获
异常:程序在运行时出现的不正常现象 Throwable |——Error |——Exception 严重级别:Error类和Exception类 异常的处理:try{}catch{}finally{} ...
- 有关于异常捕获点滴,plus我也揭揭java的短
▄︻┻┳═一『异常捕获系列』Agenda: ▄︻┻┳═一有关于异常捕获点滴,plus我也揭揭java的短 ▄︻┻┳═一根据异常自定义处理逻辑([附]java异常处理规范) ▄︻┻┳═一利用自定义异常来 ...
- JAVA并发,线程异常捕获
由于线程的特性,当我们启动了线程是没有办法用try catch捕获异常的,如下例: package com.xt.thinks21_2; import java.util.concurrent.Exe ...
- java异常捕获的一点感悟
class Annoyance extends Exception {} class Sneeze extends Annoyance {} class Human { public static v ...
- SpringBoot入门教程(十九)@ControllerAdvice+@ExceptionHandler全局捕获Controller异常
在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler.@InitBinder.@ModelAttribute,并应用到所有@Requ ...
随机推荐
- Vue 学习之路(一)- 创建脚手架并创建项目
安装脚手架 命令 npm install -g @vue/cli 打开 cmd 窗口输入以上命令.当出现以下界面即表示安装完成. 查看已安装脚手架版本 命令 vue -V 在 cmd 窗口输入以上命令 ...
- 聊聊如何在华为云IoT平台进行产品开发
摘要:华为云物联网平台承载着南北向数据互通的功能职责. 本文分享自华为云社区<如何基于华为云IoT物联网平台进行产品开发>,作者: Super.雯 . 华为云物联网平台承载着南北向数据互通 ...
- MeteoInfo-Java解析与绘图教程(八)_java解析卫星FY-4A一级产品文件(HDF举例)
MeteoInfo-Java解析与绘图教程(八)_java解析卫星一级产品文件(HDF举例) 最近解析卫星数据遇到了一级产品,它的解析方式与之前文章说的有些不同,特此补充一下 卫星的一级产品,里面是没 ...
- 史上最全Redis面试题(2020最新版)
一个执着于技术的公众号 导读:2020 年最新版 Redis面试题,两万字干货,为方便读者阅读,已整理为PDF文档,后台回复『redis』即可领取.希望对大家有帮助! 概述 1. 什么是Redis? ...
- svelte组件:svelte3.x自定义美化虚拟滚动条组件svelte-scrollbar
基于svelte3.0自定义pc端虚拟滚动条组件svelteScrollbar. svelte-scrollbar:运用svelte3.x创建的桌面pc版自定义美化滚动条组件.支持是否原生滚动条.自动 ...
- DOM0级同DOM2级
DOM0级分为两个:一是写在标签内的onclick事件: <button id="btn" onclick="alert('happy')">按钮& ...
- 太极限了,JDK的这个BUG都能被我踩到
hello,大家好呀,我是小楼. 之前遇到个文件监听变更的问题,刚好这周末有空研究了一番,整理出来分享给大家. 从一次故障说起 我们还是从故障说起,这样更加贴近实际,也能让大家更快速理解背景. 有一个 ...
- SpringBoot项目使用jasypt加解密
Jasypt 是一个 Java 库,它允许开发者以最小的努力为他 / 她的项目添加基本的加密功能,而且不需要对密码学的工作原理有深刻的了解. 一.添加依赖 <dependency> < ...
- 数仓选型必列入考虑的OLAP列式数据库ClickHouse(中)
实战 案例使用 背景 ELK作为老一代日志分析技术栈非常成熟,可以说是最为流行的大数据日志和搜索解决方案:主要设计组件及架构如下: 而新一代日志监控选型如ClickHouse.StarRocks特别是 ...
- 历经70+场面试,我发现了大厂面试的bug,并总结其中心得
想起了学弟在去年秋招时面试了50余家,加上暑期实习面试了20余家,加起来也面试了70余场. 基本把国内有名的互联网公司都面了一遍,不敢说自己的面试经验很丰富,但也是不差的. 这次专门把大厂的面试做了个 ...