springboot自定义异常
SpringBoot自定义异常以及异常处理
在web项目中,我们可能需要给前端返回不同的提示码。例如:401表示没有权限,500代表位置异常,200代表请求成功等。但是这些提示码远远不能满足我们返回给前端的提示,可能还需要我们自定义错误码给前端,前端获取相应的错误码以及错误信息,展示到页面中。
使用自定义异常可以解决这些返回值,利用自定义异常以及对异常的处理,可以在返回的时候自定义我们的返回码以及错误信息等。
一、自定义异常类
/**
* @author: lxw
* @Date: 2019/2/16 20:00
* @email:
* @Description: 自定义异常(继承运行时异常)
*/
public class ExceptionUtils extends RuntimeException { private static final long serialVersionUID = 1L; /**
* 错误编码
*/
private int code; /**
* 消息是否为属性文件中的Key
*/
private boolean propertiesKey = true; /**
* 构造一个基本异常.
*
* @param message 信息描述
*/
public ExceptionUtils(String message) {
super(message);
} /**
* 构造一个基本异常.
*
* @param code 错误编码
* @param message 信息描述
*/
public ExceptionUtils(int code, String message) {
this(code, message, true);
} /**
* 构造一个基本异常.
*
* @param code 错误编码
* @param message 信息描述
*/
public ExceptionUtils(int code, String message, Throwable cause) {
this(code, message, cause, true);
} /**
* 构造一个基本异常.
*
* @param code 错误编码
* @param message 信息描述
* @param propertiesKey 消息是否为属性文件中的Key
*/
public ExceptionUtils(int code, String message, boolean propertiesKey) {
super(message);
this.setCode(code);
this.setPropertiesKey(propertiesKey);
} /**
* 构造一个基本异常.
*
* @param code 错误编码
* @param message 信息描述
*/
public ExceptionUtils(int code, String message, Throwable cause, boolean propertiesKey) {
super(message, cause);
this.setCode(code);
this.setPropertiesKey(propertiesKey);
} /**
* 构造一个基本异常.
*
* @param message 信息描述
* @param cause 根异常类(可以存入任何异常)
*/
public ExceptionUtils(String message, Throwable cause) {
super(message, cause);
} public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public boolean isPropertiesKey() {
return propertiesKey;
} public void setPropertiesKey(boolean propertiesKey) {
this.propertiesKey = propertiesKey;
} }
二、自定义异常处理
import com.modules.common.utils.RUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException; /**
* @author: lxw
* @Date: 2019/2/16 20:00
* @email:
* @Description: 自定义异常处理
*/
@RestControllerAdvice
public class RExceptionUtilsHandler {
private Logger logger = LoggerFactory.getLogger(getClass()); /**
* 处理自定义异常
*/
@ExceptionHandler(ExceptionUtils.class)
public RUtils handleRRException(ExceptionUtils e) {
RUtils r = new RUtils();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
} /**
* 未找到路径异常处理
*/
@ExceptionHandler(NoHandlerFoundException.class)
public RUtils handlerNoFoundException(Exception e) {
logger.error(e.getMessage(), e);
return RUtils.error(404, "路径不存在,请检查路径是否正确");
} /**
* 数据库异常处理
*/
@ExceptionHandler(DuplicateKeyException.class)
public RUtils handleDuplicateKeyException(DuplicateKeyException e) {
logger.error(e.getMessage(), e);
return RUtils.error("数据库中已存在该记录");
} /**
* 普通异常处理
*/
@ExceptionHandler(Exception.class)
public RUtils handleException(Exception e) {
logger.error(e.getMessage(), e);
return RUtils.error();
}
}
三、自定义返回
package com.modules.common.utils; import java.util.HashMap;
import java.util.Map; /**
* @author: lxw
* @Date: 2019/2/19 11:19
* @email:
* @Description: 自定义返回值
*/
public class RUtils extends HashMap<String, Object> {
private static final long serialVersionUID = 1L; /**
* 默认正常返回,使用new RUtils()就可以返回
*/
public RUtils() {
put("code", 0);
} /**
* 表示异常
*/
public static RUtils error() {
return error(500, "未知异常,请联系管理员");
} public static RUtils error(String msg) {
return error(500, msg);
} /**
* 自定义异常错误码
*/
public static RUtils error(int code, String msg) {
RUtils r = new RUtils();
r.put("code", code);
r.put("msg", msg);
return r;
} /**
* 带信息的正常返回
*/
public static RUtils ok(String msg) {
RUtils r = new RUtils();
r.put("msg", msg);
return r;
} public static RUtils ok(Map<String, Object> map) {
RUtils r = new RUtils();
r.putAll(map);
return r;
} public static RUtils ok() {
return new RUtils();
} @Override
public RUtils put(String key, Object value) {
super.put(key, value);
return this;
}
}
四、测试输出
/**
* @author: lxw
* @Date: 2018/10/19 19:36
* @email: 1229703575@qq.com
* @Description: 测试文件
*/
@RestController
@RequestMapping("/")
public class TestController {
/**
* 测试自定义异常
*
* @return RUtils
*/
@ApiOperation(value = "测试自定义异常", notes = "测试自定义异常")
@GetMapping(value = "/exceptionTest")
public RUtils exceptionTest() {
String msg = new ExceptionUtils(500, "测试异常").getMessage();
int errorCode = new ExceptionUtils(500, "测试异常").getCode();
return RUtils.error(errorCode, msg);
}
}
五、输出结果
{"msg":"测试异常","code":500}
springboot自定义异常的更多相关文章
- springboot自定义异常视图
一.源码分析 先看源码再写自己的自定义异常视图 resolveErrorView()函数首先调用了一个返回ModelAndView的函数,该函数所需的参数是一个状态码的字符串,和一个m ...
- springboot自定义异常数据
一.源码分析 自定义异常数据之前我们先看看一下源码 上述代码意思是如果你没有提供就使用springboot提供的类 这是springboot提供的异常属性类,我们想要自 ...
- 源码剖析Springboot自定义异常
博主看到新服务是封装的自定义异常,准备入手剖析一下,自定义的异常是如何进行抓住我们请求的方法的异常,并进行封装返回到.废话不多说,先看看如何才能实现封装异常,先来一个示例: @ControllerAd ...
- springboot自定义异常页面
废话不多,直接开始. 项目目录: 说明:springboot 静态文件放在static目录中,如images中放的图片:templates目录下error中存放的是错误页面,如500.html代表50 ...
- SpringBoot自定义异常,优雅解决业务逻辑中的错误
概要 你是不是在为业务逻辑中出现的异常弄的焦头烂额,常常在后台报错,前端却无法提示错误内容,导致用户体验极差?比如下单失败,前端只能提示下单失败,但是却不知道为什么失败,是库存不足,还是余额不足,亦或 ...
- springboot自定义异常RESTful返回异常
1.自定义异常类 package com.zhx.common.exception; import com.zhx.common.model.ErrorCode; /** * @Author: Sim ...
- 测试开发专题:spring-boot自定义异常返回
上文测试开发专题:spring-boot统一异常捕获我们讨论了java异常以及如何使用Spring-Boot捕获异常,但是没有去说捕获异常后该如何进一步处理,这篇文章我们将对这个遗留的问题进行讨论. ...
- 转:SpringBoot 自定义异常@ContollerAdvice ExceptionHandler不起作用
原文链接:https://blog.csdn.net/evanxuhe/article/details/78650979 为了统一异常,我们通常定义一个统一管理所有Exception,包括自定义Exc ...
- 【SpringBoot】单元测试进阶实战、自定义异常处理、t部署war项目到tomcat9和启动原理讲解
========================4.Springboot2.0单元测试进阶实战和自定义异常处理 ============================== 1.@SpringBoot ...
随机推荐
- 比较旧的写法:验证车牌、手机号、电话、qq等
1.验证车牌代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...
- “全栈2019”Java第七十章:静态内部类详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- 微信小程序之tabbar切卡
最近在研究小程序的时候,遇到了一个问题,就是tabbar切卡,在android上有fragment,在RN上也有提供一个第三方的组件来用,微信小程序,好像没有专门的一个组件来实现这个功能,度娘了大半天 ...
- [ActionScript 3.0] 简单倒计时
import flash.utils.Timer; import flash.events.TimerEvent; import flash.text.TextField; var text:Text ...
- Intellig IDEA 搭建spring boot 热部署
在pom中直接引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...
- P5283 [十二省联考2019]异或粽子 可持久化01Trie+线段树
$ \color{#0066ff}{ 题目描述 }$ 小粽是一个喜欢吃粽子的好孩子.今天她在家里自己做起了粽子. 小粽面前有 \(n\) 种互不相同的粽子馅儿,小粽将它们摆放为了一排,并从左至右编号为 ...
- css 清楚浮动三种方法
我们可以看到这样一个布局: <style> .left{ width: 200px; height: 200px; background-color: #00ee00; float: le ...
- SD与SE的关系,以及异常值
很多刚进入实验室的同学对实验数据的标准差(SD)与标准误(SE)的含义搞不清,不知道自己的数据报告到底该用SD还是SE.这里对这两个概念进行一些介绍. 标准差(SD)强调raw data的Variat ...
- 【算法笔记】B1033 旧键盘打字
1033 旧键盘打字 (20 分) 旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现.现在给出应该输入的一段文字.以及坏掉的那些键,打出的结果文字会是怎样? 输入格式: 输入在 2 行 ...
- 微信小程序回到顶部的两种方式
一,使用view形式的回到顶部 <image src='../../img/button-top.png' class='goTop' hidden='{{!floorstatus}}' bin ...