Springboot处理异常的常见方式

网友投稿 582 2023-01-14

Springboot处理异常的常见方式

Springboot处理异常的常见方式

一、制造异常

SbDINlsMr

报500错误。在大量的代码中很难找到错误

二、统一异常处理

添加异常处理方法

GlobalExceptionHandler.java中添加

//指定出现什么异常执行这个方法

@ExceptionHandler(Exception.class)

@ResponseBody //为了返回数据

public R error(Exception e) {

e.printStackTrace();

return R.error().message("执行了全局异常处理..");

}

报错异常:在大型项目中,可对多种异常进行处理,便于找bug

三、特殊异常处理

定义异常,特别处理ArithmeticException异常

//特定异常处理

@ExceptionHandler(ArithmeticException.class)

@ResponseBody//为了返回数据

public R error(ArithmeticException e){

e.printStackTrace();

return R.error(http://).message("执行了ArithmeticException异常处理");

}

异常处理结果:

四、自定义异常处理

第一步:创建自定义处理类的实体类:

@Data

@AllArgsConstructor//生成有参构造方法

@NoArgsConstructor//生成无参构造方法

public class MyException extends RuntimeException{

private Integer code;

private String msg;

}

第二步:在统一异常类中添加规则:

//自定义异常处理

@ExceptionHandler(MyException.class)

@ResponseBody//返回数据

public R error(MyException e){

e.printStackTrace();

return R.error().code(e.getCode()).message(e.getMsg());//封装自定义异常信息

}

第三步:执行自定义异常

try{

int i=10/0;

}catch (Exception e){

throw new MyException(20001,"执行自定义异常处理");

}

以上使用的R类,用于封装json数据的格式:

@Data

public class R {

@ApiModelProperty(value = "是否成功")

private Boolean success;

@ApiModelProperty(value = "返回码")

private Integer code;

@ApiModelProperty(value = "返回消息")

private String message;

@ApiModelProperty(value = "返回数据")

private Map data = new HashMap();

private R(){}

public static R ok(){

R r = new R();

r.setSuccess(true);

r.setCode(ResultCode.SUCCESS);

r.setMessage("成功");

return r;

}

public static R error(){

R r = new R();

r.setSuccess(false);

r.setCode(ResultCode.ERROR);

r.setMessage("失败");

return r;

}

public R success(Boolean success){

this.setSuccess(success);

return this;

}

public R message(String message){

this.setMessage(message);

return this;

}

public R code(Integer code){

this.setCode(code);

return this;

}

public R data(String key, Object value){

this.data.put(key, value);

return this;

}

public R data(Map map){

this.setData(map);

return this;

}

}

public interface ResultCode {

public static Integer SUCCESS = 20000;

public static Integer ERROR = 20001;

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:小程序生态海报怎么做模板(小程序生态海报怎么做模板的)
下一篇:企业app开发价格(app程序开发报价)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~