博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot 统一异常处理
阅读量:2491 次
发布时间:2019-05-11

本文共 4914 字,大约阅读时间需要 16 分钟。

目的:

无论请求是否成功,均返回格式一样的数据,方便前端等操作。

如:

{
"code":0,"msg":"成功","data":{
"id":5,"age":19,"name":"xiongsiyu"}}
{
"code":1,"msg":"未满18岁禁止访问","data":null}

1、新建结果类

package cn.edu.shu.ces_chenjie.pojo;public class Result
{ /** 错误码 **/ private Integer code; /** 提示信息 **/ private String msg; /** 具体内容 **/ private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; }}

2、新增工具类

package cn.edu.shu.ces_chenjie.utils;import cn.edu.shu.ces_chenjie.pojo.Result;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(){        Result result = new Result();        result.setCode(0);        result.setMsg("成功");        result.setData(null);        return result;    }    public static Result error(Integer code,String msg){        Result result = new Result();        result.setCode(code);        result.setMsg(msg);        result.setData(null);        return result;    }}

3、修改方法

@PostMapping("/persons")    public Result
personAdd(@Valid Person person, BindingResult bindingResult){ if(bindingResult.hasErrors()){ System.out.println(bindingResult.getFieldError().getDefaultMessage()); return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage()); } return ResultUtil.success(repository.save(person)); }

4、测试

二、获取用户的年龄并判断

当出现Exception时,不会按照此前定义的Result来返回结果,而是返回异常信息,

想要实现:出现异常时能改捕获异常,还是按照Result的格式返回

1、在service中增加代码

public void getAge(Integer id) throws Exception {        Person person = repository.findOne(id);        Integer age = person.getAge();        if(age<10)        {            throw new Exception("你还在上小学吧");        }        else if(age>10 && age <16){            throw new Exception("你可能在上初中");        }    }
2、在controller中调用

@RequestMapping("persons/getAge/{id}")    public void getAge(@PathVariable("id")Integer id) throws Exception {        personService.getAge(id);    }
3、定义异常处理类

package cn.edu.shu.ces_chenjie.handle;import cn.edu.shu.ces_chenjie.pojo.Result;import cn.edu.shu.ces_chenjie.utils.ResultUtil;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;@ControllerAdvicepublic class ExceptionHandle {    @ExceptionHandler(value = Exception.class)    @ResponseBody    public Result handle(Exception e){        return ResultUtil.error(100, e.getMessage());    }}
4、运行

3、如果只捕获Exception,只能获得一个Msg,如何获得更多信息?

自定义Exception

public class PersonException extends RuntimeException{    private Integer code;    public PersonException(Integer code,String msg){        super(msg);        this.code = code;    }    public Integer getCode() {        return code;    }    public void setCode(Integer code) {        this.code = code;    }}
修改service代码:

public void getAge(Integer id) throws PersonException {        Person person = repository.findOne(id);        Integer age = person.getAge();        if(age<10)        {            throw new PersonException(101,"你还在上小学吧");        }        else if(age>10 && age <16){            throw new PersonException(102,"你可能在上初中");        }    }
修改处理类:

@ControllerAdvicepublic class ExceptionHandle {    @ExceptionHandler(value = Exception.class)    @ResponseBody    public Result handle(Exception e){        if(e instanceof PersonException)        {            PersonException exception = (PersonException) e;            return ResultUtil.error(exception.getCode(), e.getMessage());        }        return ResultUtil.error(100, e.getMessage());    }}
运行:

三、如何维护错误状态码和状态信息?

使用枚举

package cn.edu.shu.ces_chenjie.enums;public enum  ResultEnum {     UNKNOWN_ERROR(-1,"未知错误"),    SUCCESS(0,"成功"),    PRIMARY(100,"你可能还在上小学"),    MIDDLE(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;    }}
修改PersonException

package cn.edu.shu.ces_chenjie.exception;import cn.edu.shu.ces_chenjie.enums.ResultEnum;public class PersonException extends RuntimeException{    private Integer code;    public PersonException(ResultEnum resultEnum){        super(resultEnum.getMsg());        this.code = resultEnum.getCode();    }    public Integer getCode() {        return code;    }    public void setCode(Integer code) {        this.code = code;    }}

你可能感兴趣的文章
第一轮面试题
查看>>
2020-11-18
查看>>
Docker面试题(二)
查看>>
一、redis面试题及答案
查看>>
消息队列2
查看>>
C++ 线程同步之临界区CRITICAL_SECTION
查看>>
测试—自定义消息处理
查看>>
MFC中关于虚函数的一些问题
查看>>
根据图层名获取图层和图层序号
查看>>
规范性附录 属性值代码
查看>>
提取面狭长角
查看>>
Arcsde表空间自动增长
查看>>
Arcsde报ora-29861: 域索引标记为loading/failed/unusable错误
查看>>
记一次断电恢复ORA-01033错误
查看>>
C#修改JPG图片EXIF信息中的GPS信息
查看>>
从零开始的Docker ELK+Filebeat 6.4.0日志管理
查看>>
How it works(1) winston3源码阅读(A)
查看>>
How it works(2) autocannon源码阅读(A)
查看>>
How it works(3) Tilestrata源码阅读(A)
查看>>
How it works(12) Tileserver-GL源码阅读(A) 服务的初始化
查看>>