基于spring boot的统一异常处理
一、springboot的默认异常处理
Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容。
例如这里我们认为制造一个异常
@GetMapping(value = "/boys")
public List<Boy> boyList() throws Exception{
throw new Exception("错误");
}
使用浏览器访问http://127.0.0.1:8080/boys

二、自定义的统一异常处理
虽然Spring Boot中实现了默认的error映射,但是在实际应用中,上面你的错误页面对用户来说并不够友好,我们通常需要去实现我们自己的异常提示。
1) 统一的异常处理类(com.dechy.handle)
@ControllerAdvice
public class ExceptionHandle { private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof BoyException) {
BoyException boyException = (BoyException) e;
return ResultUtil.error(boyException.getCode(), boyException.getMessage());
}else {
logger.error("【系统异常】{}", e);
return ResultUtil.error(-, "未知错误");
}
}
}
2)自定义异常类(com.dechy.exception)
public class BoyException extends RuntimeException{
private Integer code;
public BoyException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
3)返回结果枚举(com.dechy.enums)
public enum ResultEnum {
UNKONW_ERROR(-, "未知错误"),
SUCCESS(, "成功"),
TOOSHORT(, "身高太矮"),
TOOHIGH(, "身高太高"),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
4)返回结果工具类(com.dechy.util)
public class ResultUtil {
public static Result success(Object object) {
Result result = new Result();
result.setCode();
result.setMsg("成功");
result.setData(object);
return result;
}
public static Result success() {
return success(null);
}
public static Result error(Integer code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
5)Boy实体类(com.dechy.model)
@Entity
public class Boy { @Id
@GeneratedValue
private Integer id; @NotBlank(message = "这个字段必传")
private String height; @Min(value = 100, message = "体重必须大于100")
private BigDecimal weight; public Integer getId (){
return id;
} public void setId (Integer id){
this.id = id;
} public String getHeight (){
return height;
} public void setHeight (String height){
this.height = height;
} public BigDecimal getWeight (){
return weight;
} public void setWeight (BigDecimal weight){
this.weight = weight;
} @Override
public String toString (){
return "Boy{" + "id=" + id + ", height='" + height + '\'' + ", weight=" + weight + '}';
}
}
6)业务层具体使用时抛出异常,等待统一处理(com.dechy.service)
public void chooseBoy(Integer id) throws Exception{
Boy boy= boyRepository.findOne(id);
Integer height= boy.getHeight();
if (height < 100) {
//返回"身高矮" code=100
throw new BoyException(ResultEnum.TOOSHORT);
}else if (height > 200) {
//返回"身高太高" code=101
throw new BoyException(ResultEnum.TOOHIGH);
}//...
}
基于spring boot的统一异常处理的更多相关文章
- 基于Spring Boot的统一异常处理设计
基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支 ...
- spring boot 中统一异常处理
基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常 步骤一:自定义异常类 public class UserNotExistException extends Runt ...
- spring boot配置统一异常处理
基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...
- Spring Boot实践——统一异常处理
注解说明 @ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: /** * Special ...
- Spring Boot学习——统一异常处理
本随笔记录使用Spring Boot统一处理异常. 本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间.小于14岁,提示“你可能在上初中”:大于20岁,提示“呢可能在上大学” ...
- 【Spring Boot】Spring Boot之统一异常处理
一.统一异常处理的作用 在web应用中,请求处理时,出现异常是非常常见的.所以当应用出现各类异常时,进行异常的统一捕获或者二次处理(比如空指针异常或sql异常正常是不能外抛)是非常必要的,然后右统一异 ...
- spring boot 2 统一异常处理
spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestContr ...
- 基于Spring Boot和Spring Cloud实现微服务架构学习
转载自:http://blog.csdn.net/enweitech/article/details/52582918 看了几周Spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习感 ...
- 基于Spring Boot和Spring Cloud实现微服务架构学习--转
原文地址:http://blog.csdn.net/enweitech/article/details/52582918 看了几周spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习 ...
随机推荐
- zabbix 分布式zabbix_proxy
Zabbix是一个分布式监控系统,它可以以一个中心点.多个分节点的模式运行,使用Proxy能大大的降低Zabbix Server的压力,Zabbix Proxy可以运行在独立的服务器上 1)下载zab ...
- 'Could not find first log file name in binary log index file'的解决办法
数据库主从出错: Slave_IO_Running: No 一方面原因是因为网络通信的问题也有可能是日志读取错误的问题.以下是日志出错问题的解决方案: Last_IO_Error: Got fatal ...
- RPN(region proposal network)之理解
在faster-r-cnn 中,因为引入rpn层,使得算法速度变快了不少,其实rpn主要作用预测的是 “相对的平移,缩放尺度”,rpn提取出的proposals通常要和anchor box进行拟合回归 ...
- atrous convolution
atrous convolution 简而言之,带孔卷积: 来自:https://zhuanlan.zhihu.com/p/27470685 假设一个二维信号,每个位置对应的输出为和卷积核为,带孔卷积 ...
- kotlin string
Kotlin String split 操作实践 内容 此文章展示kotlin中对String字符串的split操作,如果你有遇到这方面的需求,希望对你有用. 1. split + 正则 先看下系 ...
- 小程序-setData
根据下标修改数组中的key: var id = e.target.id//根据点击不同的view获取对应的id值 var str = "isChecked[" + id + &qu ...
- flume 实际的使用
1.No configuration found for this host:seqGenSrc bin/flume-ng agent --conf conf --conf-file conf/flu ...
- kangle请求控制添加的add_header怎么查看
请求控制里添加的add header不会显示在浏览器的请求里,因为是发送给源的,你们要查看可以用phinfo查看.回应控制里添加的会显示在浏览器的回应里
- python--第三天总结
[collection系列]1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能 c = Counter('abcdeabc ...
- php判断文件夹是不是存在
function MkFolder($path){ if(!is_readable($path)){ MkFolder( dirname($path) ); if(!is_file ...