一、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的统一异常处理的更多相关文章

  1. 基于Spring Boot的统一异常处理设计

    基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支 ...

  2. spring boot 中统一异常处理

    基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常 步骤一:自定义异常类 public class UserNotExistException extends Runt ...

  3. spring boot配置统一异常处理

    基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...

  4. Spring Boot实践——统一异常处理

    注解说明 @ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: /** * Special ...

  5. Spring Boot学习——统一异常处理

    本随笔记录使用Spring Boot统一处理异常. 本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间.小于14岁,提示“你可能在上初中”:大于20岁,提示“呢可能在上大学” ...

  6. 【Spring Boot】Spring Boot之统一异常处理

    一.统一异常处理的作用 在web应用中,请求处理时,出现异常是非常常见的.所以当应用出现各类异常时,进行异常的统一捕获或者二次处理(比如空指针异常或sql异常正常是不能外抛)是非常必要的,然后右统一异 ...

  7. spring boot 2 统一异常处理

    spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestContr ...

  8. 基于Spring Boot和Spring Cloud实现微服务架构学习

    转载自:http://blog.csdn.net/enweitech/article/details/52582918 看了几周Spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习感 ...

  9. 基于Spring Boot和Spring Cloud实现微服务架构学习--转

    原文地址:http://blog.csdn.net/enweitech/article/details/52582918 看了几周spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习 ...

随机推荐

  1. Arcgis map export or print Error: Cannot map metafile into memory. Not enough memory

      Arcgis map export or print Error: Cannot map metafile into memory. Not enough memory Link: https:/ ...

  2. 面试官提出的问题应该怎么答?(如开发中使用过EasyUI吗?)

    Jquery EasyUI是第三方基于Jquery框架开发的一款轻量级的,侧重于页面显示部分的框架,也可以称为插件. Jquery EasyUI使用比较简单,也有比较全的文档可供参考. 常用的组件就是 ...

  3. Numpy知识(一)

    先了解ndarray(一个多维数组)的生成. 第一种生成方法就是np.random.randn(n,m),这回生成一个形状是n*m的ndarray.如下图. 第二种生成方法:传入一个列表listDem ...

  4. css 鼠标选中内容背景色

    ::selection { background: rgba(32, 178, 170, .6); color: #ffffff; } ::-moz-selection { background: r ...

  5. MyBatis数据库连接的基本使用-补充

    补充1  MyBatis使用过程中,返回值类型可能是Map,不一定是实体类 返回查询结果也可以是一个Map,不一定是实体类 (1)mybatis会先将查询结果返回为一个map,字段名作为key,字段值 ...

  6. linux删除历史操作命令

    有时候在系统中做了任何操作,但不想被别人知道,毕竟系统别人都可以登入查看,那怎么把自己操作系统的历史命令删除而不让别人知晓呢? 在linux系统里一旦操作了任何命令,都会被记录下来,可以通过histo ...

  7. Idea设置类注释模板

    1.选择File–>Settings–>Editor–>File and Code Templates–>Includes–>File Header. 在Descript ...

  8. Android笔记:intent

    一.显式intent如下:(1)在intent构造函数传入两个activity文件名Intent intent = new Intent(FirstActivity.this, SecondActiv ...

  9. Centos 7 下 Mysql 5.7 Galera Cluster 集群部署

     一.介绍 传统架构的使用,一直被人们所诟病,因为MySQL的主从模式,天生的不能完全保证数据一致,很多大公司会花很大人力物力去解决这个问题,而效果却一般,可以说,只能是通过牺牲性能,来获得数据一致性 ...

  10. verilog task2

    1.问题:串口的发送和接收 系统时钟50Mhz,波特率119200.系统时钟计数约2604个,才是一位数据的传输时间. 模拟接收的任务函数rx_data_task():LSB first task r ...