一、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. curl命令解析

    curl命令可以实现http post或者get的请求,是linux下的命令行工具 1.1.直接请求url,打印标准输出 1.2.使用-o参数,可以标准输出到指定的位置 [root@VM-3-10-1 ...

  2. asp.net 如何判断输入的值 包括 汉字?

    string input = " 里面是不是汉字 ";bool bl= System.Text.RegularExpressions.Regex.IsMatch(input, @& ...

  3. Feign Hystrix

    1.Feign整合Hystrix 添加依赖 编写接口与实现回退 1.1.调用者引入依赖 <!-- Feign --> <dependency> <groupId>o ...

  4. 工单进入IN_MO后在FP_PREPROCESS被过滤

    '; --BOM and item not in IN_ITEMBOMROUTING SELECT * FROM TEMP_REMOVED_IN_DATA WHERE TABLE_NAME='IN_M ...

  5. Struts2学习资料

    Struts2入门示例教程 http://blog.csdn.net/wwwgeyang777/article/details/19078545     Struts2工作原理 http://blog ...

  6. 安卓下H5弹窗display:table的bug

    表单以弹窗的形式弹出时,若设置了表单的div:display:table下,安卓打开页面输入法的时候,表单顶到屏幕顶部之后,再也无法上滑,键盘遮住了下面的输入框.在ios下,一切显示正常,因为iOS会 ...

  7. helm 更改为国内源

     helm init --upgrade -i slpcat/tiller:v2.8.2 --stable-repo-url https://kubernetes.oss-cn-hangzhou.al ...

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

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

  9. HDU-1212.BigNumber(有关模数的定理)

    本题大意:给出一个1000位以内的大数和一个小数,让你计算并给出大数对小数取余的结果. 本题思路:由下面的公式可以推出本题的计算公式,套入即可解决,建议自己把这个公式推一下,很简单的... 参考代码: ...

  10. Codeforces Beta Round #29 (Div. 2, Codeforces format)

    Codeforces Beta Round #29 (Div. 2, Codeforces format) http://codeforces.com/contest/29 A #include< ...