springboot2.x如何配置全局自定义异常

为什么要捕获异常?


我们开发中,经常运行时,代码会报错,这时候我们有可能抛出异常,而不是用try..catch来解决.而且现在前后端分离,如果不捕获异常的话,前端那边的人估计会被报的错搞得焦头烂额的.

springboot2.x是怎么自定义异常的?怎么捕获异常的?


我们自定义异常类,需要继承一个RuntimeException父类,并且包装好自己的异常类,一般是包装code(错误码),msg(错误信息).

/**
* 自定义异常类
*/
public class TestException extends RuntimeException{

Integer code;
String msg;

public TestException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}

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;
}
}


接着我们需要创建一个异常处理器,这里是来捕获异常的.
/**
* 异常处理控制器
*/
@ControllerAdvice
public class TestExceptionHandler {

@ExceptionHandler(value = Exception.class) //一般是捕获最高级的exception类,或者你想捕获单独的一个异常类(比如我们前面创建的TestException,不过推荐这种,相对简洁)
@ResponseBody //返回数据以json数据传输
public JsonData Handler(Exception e){ //jsonData是我自定义的一个包装类,主要用于传输给前端的数据
if(e instanceof TestException){ //判断异常类型
TestException testException = (TestException) e;
return JsonData.buildError(testException.getMsg(),testException.getCode());
}else{
return JsonData.buildError("全局异常,未知错误!");
}
}
}




猜你喜欢

转载自www.cnblogs.com/zexin/p/10211740.html