SpringBoot 统一异常处理

来源:互联网 发布:淘宝网直通车怎么开 编辑:程序博客网 时间:2024/06/06 04:33

目的:

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

如:

{"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<T> {    /** 错误码 **/    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<Person> 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;    }}