一、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. 基于Java SE集合的图书管理系统

    图书管理系统一.需求说明1.功能:登录,注册,忘记密码,管理员管理,图书管理.2.管理员管理:管理员的增删改查.3.图书管理:图书的增删改查.4.管理员属性包括:id,姓名,性别,年龄,家庭住址,手机 ...

  2. 3dmax快捷键

    P 透视图 F前视图 L 左视图 T 顶视图 B 底视图单窗口与四窗口的切换快捷键是 alt+w 渲染快捷键 shilf+q 独立 快捷键 alt+q 自己多记点快捷键哦!!!!3DMAX2009快捷 ...

  3. spring boot 项目配置字符编码

  4. eclipse git 忽略文件

    ps:git中只有.gitignore文件需要先加索引再提交,其它的都可以直接提交

  5. CSS 原理

    CSS是一个描述HTML文档的样式语言. CSS描述HTML元素的显示方式. 本教程将教你CSS从基础到网页布局,学完本教程,可以设计出漂亮的网站. 本教程需要HTML知识为基础,学习HTML前往&l ...

  6. pyhton笔记(一):字符编码、变量

    一.什么是python? python是一种面向对象.解释型的计算机语言,它的特点是语法简洁.优雅.简单易学. 编译型语言: 写好代码之后把代码编译成二进制文件,运行时运行编译好的二进制文件.比如C. ...

  7. 使用in ()进行批量删除

    public bool DeleteList(string idlist ) { StringBuilder strSql=new StringBuilder(); strSql.Append(&qu ...

  8. shiro 入门

    参考文章: https://www.cnblogs.com/maofa/p/6407102.html https://www.cnblogs.com/learnhow/p/9747134.html h ...

  9. Redis 总结

    Redis官网下载地址: https://redis.io/ Redis 客户端可视化:https://redisdesktop.com/download 一.Redis 是什么? 1.key-val ...

  10. PERL 正则表达式简介

    来源:脚本之家 网址:http://www.jb51.net/article/17429.htm 一.简介 二.匹配操作符 三.模式中的特殊字符 1.字符+ 2.字符 []和[^] 3.字符 *和? ...