基于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,是时候开始总结下这中间的学习 ...
随机推荐
- servlet 验证码生成
servlet package com.htpo.net; import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D; ...
- FMS Dev Guide学习笔记(验证客户端)
一.开发交互式的媒体应用程序 1.使用客户端对象的属性 当一个客户端连接上服务器上的一个应用,服务端就会创建一个包含这个客户端信息的客户端对象并且将它传递给application.onConn ...
- 吴裕雄 python深度学习与实践(5)
import numpy as np data = np.mat([[1,200,105,3,False], [2,165,80,2,False], [3,184.5,120,2,False], [4 ...
- 吴裕雄 python 爬虫(4)
import requests user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, li ...
- GBDT+Lr
https://blog.csdn.net/shine19930820/article/details/71713680 http://scikit-learn.org/stable/auto_exa ...
- cd-hit软件
参考网址:https://www.jianshu.com/p/57af07b9e986 1.安装 wget https://github.com/weizhongli/cdhit/releases/d ...
- git flow分支管理
阅读目录 两种核心分支 三种临时分支 Git Flow流程示例代码 Git Flow工具 分支命名规范 总结 git flow是Vincent Driessen提出了一个分支管理的策略,非常值得借鉴. ...
- jvm中堆和栈的区别
1.前言. 其实jvm能优化的空间不多,最主要的是使用的共享内存不要超过默认的2g或者自己调的参数.但了解一下还是有点意思的,建议面试时还是要看,别学笔者裸奔. 2.区别. 网上说是有5点区 ...
- series of Nimble
[nimble] series方法用于串行执行多个异步任务,通过npm可安装nimble. Series works similarly to parallel, only it runs each ...
- 算法之LOWB三人组之插入排序
插入排序 思想:类似于抽扑克牌,共有8张扑克牌,手里默认有一张,桌面上有7张,我们每次从桌面上抽一张和手里的牌进行比较,如果比手里的牌大,则直接放到手里的牌的后面,如果比手里的牌小,则放到手里的牌的前 ...