這篇文章將為大家詳細講解有關怎么在Springboot中處理異常,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

報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().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<String, Object> data = new HashMap<String, Object>();
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<String, Object> map){
this.setData(map);
return this;
}
}public interface ResultCode {
public static Integer SUCCESS = 20000;
public static Integer ERROR = 20001;
}關于怎么在Springboot中處理異常就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。