SpringBoot(七)_统一异常处理
我感觉看了这节课,给我的思考还是很多的,感觉受益良多。废话不多说,一起学习。
统一的 外层结构返回
这样利于代码看着也规范,前端处理也统一
# 错误返回
{
"code": 1,
"msg": "未成年禁止入内",
"data": null
}
# 正确返回
{
"code": 0,
"msg": "成功",
"data":{
"id": 8,
"name": "maomao",
"age": 19
}
}
(1) 实现这个我们要定义一个返回结果的实体类
package com.imooc.entity;
/**
* http请求做外层对象
* @Auther: curry
* @Date: 2018/6/2 14:35
* @Description:
*/
public class Result<T> {
/**
* 状态码
*/
private Integer code;
/**
* 提示信息
*/
private String msg;
/**
* 返回数据
*/
private T data;
//get和set省略
}
(2)定义返回结果的工具类
package com.imooc.utils;
import com.imooc.entity.Result;
/**
* @Auther: curry
* @Date: 2018/6/2 14:39
* @Description:
*/
public class ResultUtil {
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
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;
}
}
(3) 使用规定的返回结果
注意:controller 只是用于请求和参数的传递,业务处理应该在service进行处理。这只是方便演示
@PostMapping("/girls")
public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
}
return ResultUtil.success(girlRepository.save(girl));
}
(4) 这样就使我们返回结果如上面所示的一样了
定义统一的异常处理
实现业务:获取女生的年龄,
如果小于10岁:返回:还在小学
如果大于10岁小于16岁:返回:还在初中
controller层
@GetMapping(value = "/girls/getAge/{id}")
public void getAge(@PathVariable("id") Integer id) throws Exception {
girlService.getAge(id);
}
service层
@Service
public class GirlService {
@Resource
private GirlRepository girlRepository;
public void getAge(Integer id) throws Exception {
Girl girl = girlRepository.getOne(id);
Integer age = girl.getAge();
if(age<10){
throw new Exception("还在小学");
}else if(age >10 && age< 16){
throw new Exception("还在初中");
}
}
}
监听异常
package com.imooc.handle;
import com.imooc.aspect.HttpAspect;
import com.imooc.entity.Result;
import com.imooc.exception.GirlException;
import com.imooc.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Auther: curry
* @Date: 2018/6/2 15:05
* @Description:
*/
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
return ResultUtil.error(100,e.getMessage());
}
}
测试返回结果,控制台不会报错
{
"code": 100,
"msg": "还在初中",
"data": null
}
实现自己的Exception
创建自己的Exception
继承自RuntimeException 是因为 spring 这个框架对运行时异常会进行数据回滚,如果是Exception .则不会
package com.imooc.exception;
import com.imooc.enums.ResultEnum;
/**
* @Auther: curry
* @Date: 2018/6/2 15:30
* @Description:
*/
public class GirlException extends RuntimeException{
private Integer code;
// 这里使用了枚举
public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
创建枚举类
package com.imooc.enums;
/**
* @Auther: curry
* @Date: 2018/6/2 15:46
* @Description:
*/
public enum ResultEnum {
UNKNOW_ERROR(-1,"未知错误"),
SUCCESS(0,"成功"),
PRIMARY_SCHOOL(100,"还在小学"),
MIDDLE_SCHOOL(101,"还在初中"),
;
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;
}
}
修改异常捕获类
public Result handle(Exception e){
// return ResultUtil.error(100,e.getMessage());
if (e instanceof GirlException){
GirlException girlException = (GirlException)e;
return ResultUtil.error(girlException.getCode(),girlException.getMessage());
}else {
logger.info("【系统异常】{}",e);
return ResultUtil.error(-1,"未知错误");
}
}
修改service类
public void getAge(Integer id) throws Exception {
Girl girl = girlRepository.getOne(id);
Integer age = girl.getAge();
if(age<10){
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if(age >10 && age< 16){
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}
}
测试
{
"code": 101,
"msg": "还在初中",
"data": null
}
代码下载:github
玩的开心!
SpringBoot(七)_统一异常处理的更多相关文章
- SpringBoot系列——自定义统一异常处理
前言 springboot内置的/error错误页面并不一定适用我们的项目,这时候就需要进行自定义统一异常处理,本文记录springboot进行自定义统一异常处理. 1.使用@ControllerAd ...
- springboot aop + logback + 统一异常处理 打印日志
1.src/resources路径下新建logback.xml 控制台彩色日志打印 info日志和异常日志分不同文件存储 每天自动生成日志 结合myibatis方便日志打印(debug模式) < ...
- SpringBoot统一异常处理后TX-LCN分布式事务无法捕获异常进行回滚
通常我们使用SpringBoot都会进行统一异常处理,例如写一个BaseController,在BaseController里进行统一异常处理,然后其他的Controller都继承BaseContro ...
- SpringBoot系列(十)优雅的处理统一异常处理与统一结果返回
SpringBoot系列(十)统一异常处理与统一结果返回 往期推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列 ...
- SpringBoot第七集:异常处理与整合JSR303校验(2020最新最易懂)
SpringBoot第七集:异常处理与整合JSR303校验(2020最新最易懂) 一.SpringBoot全局异常 先讲下什么是全局异常处理器? 全局异常处理器就是把整个系统的异常统一自动处理,程序员 ...
- SpringBoot 统一异常处理
统一异常处理: @ControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactor ...
- 【异常处理】Springboot对Controller层方法进行统一异常处理
Controller层方法,进行统一异常处理 提供两种不同的方案,如下: 方案1:使用 @@ControllerAdvice (或@RestControllerAdvice), @ExceptionH ...
- spring 或 springboot统一异常处理
spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义 ...
- 配置springboot在访问404时自定义返回结果以及统一异常处理
在搭建项目框架的时候用的是springboot,想统一处理异常,但是发现404的错误总是捕捉不到,总是返回的是springBoot自带的错误结果信息. 如下是springBoot自带的错误结果信息: ...
随机推荐
- pycharm如何显示工具栏
1.没有工具栏的效果图如下: 2.在view中找到Toolbar打上勾即可显示: 3.工具栏设置成功显示效果图如下: 3.如何显示一个类或方法所在的文件,以及该文件下的所有方法,可以快速定位到该行
- python爬虫之requests库介绍(二)
一.requests基于cookie操作 引言:有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests模块常规操作时,往往达不到我们 ...
- Python爬虫之HTTP和HTTPS
一:HTTP和HTTPS HTTP协议(HyperText Transfer Protocol,超文本传输协议):是一种发布和接收 HTML页面的方法,以明文的形式传输,效率高,但是不安全 HTTPS ...
- yolo算法框架使用二
6,voc数据集训练模型 1)下载数据集 官网提供一些voc数据,是基于2007年到2012年的,你可以通过以下地址下载到: wget https://pjreddie.com/media/files ...
- Direct2D处理几何图形之间的碰撞检测(上)
转载请注明出处:http://www.cnblogs.com/Ray1024 一.概述 Direct2D中支持以下几种类型的几何图形: a.简单几何图形(Simple Geometry):矩形.圆角矩 ...
- 机器学习之利用KNN近邻算法预测数据
前半部分是简介, 后半部分是案例 KNN近邻算法: 简单说就是采用测量不同特征值之间的距离方法进行分类(k-Nearest Neighbor,KNN) 优点: 精度高.对异常值不敏感.无数据输入假定 ...
- thinkphp 3.x下的任意文件包含(有条件)分析
漏洞原理 实现自己的模版引擎不当,在模版渲染的情况下存在任意变量覆盖漏洞.. 漏洞详情 漏洞位置1 ThinkPHP/Library/Think/View.class.php 需要修改配置文件 指定T ...
- Python之并发编程-协程
目录 一.介绍 二. yield.greenlet.gevent介绍 1.yield 2.greenlet 3.gevent 一.介绍 协程:是单线程下的并发,又称微线程,纤程.英文名Coroutin ...
- [BUAA软工]第零次博客作业---问题回答
[BUAA软工]第0次博客作业 项目 内容 这个作业属于哪个课程 北航软工 这个作业的要求在哪里 第0次个人作业 我在这个课程的目标是 学习如何以团队的形式开发软件,提升个人软件开发能力 这个作业在哪 ...
- delphi 图像处理 图像放大缩小
procedure TDR_QM_ZP_Form.btn_FDClick(Sender: TObject); //图像放大 begin my_int1 := Trunc( my_int1 * 1.1) ...