SpringBoot全局异常处理及自定义异常
首先定义自定义返回类,如果自己项目中已经有了自定义返回类只需要将后面的代码做相应的修改即可;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 统一API对象返回
* @param <T>
* @Author: TanXJ
* @Date: 2021/10/13 9:31
*/
@Data
@NoArgsConstructor
public class ResultBean<T> {
/** 状态码 */
@ApiModelProperty(value = "状态码", example = "200")
private Integer code;
/** 返回消息 */
@ApiModelProperty(value = "返回消息", example = "操作成功")
private String message;
/** 状态 */
@ApiModelProperty(value = "状态", example = "true")
private boolean status;
/** 返回数据 */
@ApiModelProperty(value = "返回数据", example = "")
private T data;
public ResultBean(Integer code, String message, boolean status, T data) {
this.code = code;
this.message = message;
this.status = status;
this.data = data;
}
public ResultBean(ResultCode resultCode, boolean status, T data) {
this.code = resultCode.getCode();
this.message = resultCode.getMsg();
this.status = status;
this.data = data;
}
public ResultBean(ResultCode resultCode, boolean status) {
this.code = resultCode.getCode();
this.message = resultCode.getMsg();
this.status = status;
this.data = null;
}
public static <T> ResultBean success() {
return new ResultBean<>(ResultCode.OK, true);
}
public static <T> ResultBean message(String message) {
return new ResultBean<>(ResultCode.OK.getCode(), message, true, null);
}
public static <T> ResultBean success(T data) {
return new ResultBean<>(ResultCode.OK, true, data);
}
public static <T> ResultBean fail() {
return new ResultBean<>(ResultCode.ERROR, false);
}
public static <T> ResultBean fail(ResultCode resultCode) {
return new ResultBean<>(resultCode, false);
}
public static <T> ResultBean fail(Integer code, String message) {
return new ResultBean<>(code, message, false, null);
}
public static <T> ResultBean fail(ResultCode resultCode, T data) {
return new ResultBean<>(resultCode, false, data);
}
public static <T> ResultBean fail(Integer code, String message, T data) {
return new ResultBean<>(code, message, false, data);
}
}
创建全局异常处理
import com.newmap.common.response.ResultBean;
import com.newmap.common.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* @ClassName: GlobalExceptionHandler
* @Description: 全局异常处理
* @Author: TanXJ
* @Date: 2022/5/28 19:14
*/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理自定义的业务异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = CustomException.class)
@ResponseBody
public ResultBean bizExceptionHandler(HttpServletRequest req, CustomException e){
log.error("发生业务异常!原因是:{}",e.getMessage());
return ResultBean.fail(e.getCode(),e.getMessage());
}
/**
* 处理运行时异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public ResultBean runtimeExceptionHandler(HttpServletRequest req, RuntimeException e){
log.error("发生运行时异常!原因是:{}",e.getMessage());
return ResultBean.fail(500, e.getMessage());
}
/**
* 处理空指针的异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = NullPointerException.class)
@ResponseBody
public ResultBean exceptionHandler(HttpServletRequest req, NullPointerException e){
log.error("发生空指针异常!原因是:",e);
return ResultBean.fail(ResultCode.SYSTEM_ERROR);
}
/**
* 处理其他异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultBean exceptionHandler(HttpServletRequest req, Exception e){
log.error("未知异常!原因是:",e);
return ResultBean.fail(ResultCode.UNKNOWN_ERROR);
}
}
创建自定义异常处理类,这里只定义了一个自定义异常处理类,在实际的的项目中可以定义多个自定义异常处理类
import com.newmap.common.response.ResultCode;
import lombok.Getter;
/**
* @ClassName: StudentException
* @Description: 自定义异常类
* @Author: TanXJ
* @Date: 2022/5/28 19:09
*/
@Getter
public class CustomException extends RuntimeException {
private Integer code;
private String msg;
public CustomException() {
super();
}
public CustomException(ResultCode resultCode) {
super(resultCode.getMsg());
this.code = resultCode.getCode();
this.msg = resultCode.getMsg();
}
public CustomException(ResultCode resultCode, Throwable cause) {
super(resultCode.getMsg(), cause);
this.code = resultCode.getCode();
this.msg = resultCode.getMsg();
}
public CustomException(String errorMsg) {
super(errorMsg);
this.msg = errorMsg;
}
public CustomException(Integer errorCode, String errorMsg) {
super(errorMsg);
this.code = errorCode;
this.msg = errorMsg;
}
public CustomException(Integer errorCode, String errorMsg, Throwable cause) {
super(errorMsg, cause);
this.code = errorCode;
this.msg = errorMsg;
}
public Integer getErrorCode() {
return code;
}
public void setErrorCode(Integer errorCode) {
this.code = errorCode;
}
public String getErrorMsg() {
return msg;
}
public void setErrorMsg(String errorMsg) {
this.msg = errorMsg;
}
public String getMessage() {
return msg;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
代码中应用
@Override
public UserPO add(HttpServletRequest httpServletRequest, UserVO userVO) {
// 检查用户信息是否为空
if(userVO.getUserAccount() == null || userVO.getUserPassword() == null){
throw new CustomException(ResultCode.USER_INFO_IS_NULL);
}
......
SpringBoot全局异常处理及自定义异常的更多相关文章
- Springboot的异常处理与自定义异常
园友们好,元旦很快就到来了,提前祝各位园友们元旦快乐,今天给大家分享一个工作中必用一个知识点,就是使用枚举构建自定义异常并应用于springboot的异常处理器.开始之前我先把这个案例的结构大致说明一 ...
- springboot 全局异常处理
springboot 全局异常处理 研究了半天springboot的全局异常处理,虽然还是需要再多整理一下,但是对于常见的404和500足以可以区分开,能够根据这两个异常分别处理 首先配置视图解析路径 ...
- 【第二十三章】 springboot + 全局异常处理
一.单个controller范围的异常处理 package com.xxx.secondboot.web; import org.springframework.web.bind.annotation ...
- 第二十三章 springboot + 全局异常处理
一.单个controller范围的异常处理 package com.xxx.secondboot.web; import org.springframework.web.bind.annotation ...
- spring boot 全局异常处理及自定义异常类
全局异常处理: 在处理controller层抛出的自定义异常时,可以实现@ControllerAdvice注解捕获,配合@ExceptionHandler来增强所有的@requestMapping方法 ...
- SpringBoot全局异常处理方式
每个项目全局异常处理非常重要, 今天在处理项目架构的时候添加了一个全局异常处理. 大概三种异常情况: 一:在进入Controller之前,譬如请求一个不存在的地址,404错误. 二:在执行@Reque ...
- SpringBoot全局异常处理与定制404页面
一.错误处理原理分析 使用SpringBoot创建的web项目中,当我们请求的页面不存在(http状态码为404),或者器发生异常(http状态码一般为500)时,SpringBoot就会给我们返回错 ...
- SpringBoot 全局异常处理 @RestControllerAdvice +@ExceptionHandler 请求参数校验
ControllerAdvice 指示带注释的类辅助“控制器”. 作为的特殊化@Component,允许通过类路径扫描自动检测实现类. 通常用于定义@ExceptionHandler, @InitBi ...
- springboot全局异常处理(1)
新建一个类 在类上加一个注解即可 @ControllerAdvice /** * 全局错误处理 * @author sys * */ @ControllerAdvice @ResponseBody p ...
- springboot全局异常处理
@Slf4j@ControllerAdvicepublic class RestExceptionHandler extends ResponseEntityExceptionHandler { @E ...
随机推荐
- 前端使用 Konva 实现可视化设计器(12)- 连接线 - 直线
这一章实现的连接线,目前仅支持直线连接,为了能够不影响原有的其它功能,尝试了2.3个实现思路,最终实测这个实现方式目前来说最为合适了. 请大家动动小手,给我一个免费的 Star 吧~ 大家如果发现了 ...
- OpenCV简单实现AR需用到的算法函数介绍
目前的AR需求(想要达到的目标) 公司目前的需求是要能够指定一个物体开始追踪,将一张预先准备好的图像覆盖在被追踪的物体上, 然后镜头偏转缩放各类操作,再转回来仍然可以识别到,并且同样依旧覆盖图片到先前 ...
- ConfigurationManager 读取的不是最新值
用 ConfigurationManager 修改配置后,ConfigurationManager 读取的不是最新值. 解决方法: 第一种: ConfigurationManager.RefreshS ...
- C#.NET BC BouncyCastle 国密 SM2 解密遇到 Invalid point encoding 77
C#.NET BC BouncyCastle 国密 SM2 解密遇到 Invalid point encoding 77 参考:https://blog.csdn.net/seeyouagen/art ...
- 漫画图解 Go 并发编程之:Channel
当谈到并发时,许多编程语言都采用共享内存/状态模型.然而,Go 通过实现 Communicating Sequential Processes(CSP)而与众不同.在 CSP 中,程序由不共享状态的并 ...
- 🌟 简单理解 React 的 createContext 和 Provider 🚀
在 React 应用中,我们经常需要在组件之间共享状态和数据.而 React 的 createContext 和 Provider 就是为了解决这个问题而诞生的. createContext:创建自定 ...
- java8 API 函数式接口
简介 14年,Oracle公司如期发布了Java 8正式版,Java8提供了强大的流式处理及函数式接口编程 函数式接口编程,相信很多人在javascript中都使用过,比如回调函数,如今Java8也吸 ...
- 零基础写框架(3): Serilog.NET 中的日志使用技巧
.NET 中的日志使用技巧 Serilog Serilog 是 .NET 社区中使用最广泛的日志框架,所以笔者使用一个小节单独讲解使用方法. 示例项目在 Demo2.Console 中. 创建一个控制 ...
- OPC 数据采集 解决方案
笔者计划从此篇博客开始,详细介绍OPC数据采集采集过程.包括常用组态软件介绍,数据接入,OPC接入过程,常用OPC数据接入与处理全流程范例,分享相关案例Demo. 因为分享的都是个人实际工作经验中的 ...
- 【ClickHouse】0:clickhouse学习1之数据引擎(数据库引擎,表引擎)
ClickHouse提供了大量的数据引擎,分为数据库引擎.表引擎,根据数据特点及使用场景选择合适的引擎至关重要,这里根据资料做一些总结. 数据库引擎官方文档: https://clickhouse.t ...