SpringBoot进阶之使用异常替代返回错误码(拦截异常并统一处理)

来源:互联网 发布:gov.cn域名注册 编辑:程序博客网 时间:2024/06/15 07:20

直接上代码

1.Controller代码

@GetMapping(value = "/getage/{id}")public void getAge(@PathVariable("id") Integer id) throws Exception {    girlService.getAge(id);}

2.Service代码

public void getAge(Integer id ) throws Exception {    Girl girl =girlRepository.findOne(id);    Integer age= girl.getAge();    if (age<18){        throw new TGException(ResultEnum.UNDER_AGE);    }    if (age>60){        throw new TGException(ResultEnum.OLDNESS);    }}

3.TGException代码

public class TGException extends RuntimeException {    private  Integer code;    public TGException(ResultEnum resultEnum){        super(resultEnum.getMessage());        this.code=resultEnum.getCode();    }    public Integer getCode() {        return code;    }    public void setCode(Integer code) {        this.code = code;    }}
4.ResultEnum 代码   (使用枚举 将返回的返回码和返回信息维护到同一个地方)
public enum ResultEnum {    UNKONW_ERROR(-1,"未知错误"),    SUCCESS(0,"成功"),    UNDER_AGE(100,"未成年"),    OLDNESS(101,"年龄超过60岁")    ;    private Integer code;    private String message;    ResultEnum(Integer code, String message) {        this.code = code;        this.message = message;    }    public Integer getCode() {        return code;    }    public String getMessage() {        return message;    }}
5.ExceptionHandle代码(异常处理)

@ControllerAdvicepublic class ExceptionHandle {    private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);    @ResponseBody    @ExceptionHandler(value = Exception.class)    public Msg handle(Exception e){        if(e instanceof TGException){            TGException tgException=(TGException) e;            return ResultUtil.error(tgException.getCode(),tgException.getMessage());        }else {            logger.error("【系统异常】{}",e);            return ResultUtil.error(-1, "未知错误");        }    }}

附:相关注解说明

@ControllerAdvice         spring3.2新增了@ControllerAdvice 注解,

                                       可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,

                                       并应用到所有@RequestMapping中(拦截异常并统一处理)

@ExceptionHandler(value = Exception.class)     异常处理器,此注解的作用是当出现其定义的异常时进行处理的方法

@ResponseBody    该注解用于读取Request请求的body部分数据,

                              使用系统默认配置的HttpMessageConverter进行解析,

                              然后把相应的数据绑定到要返回的对象上,

                              再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。