方式一:自定义错误页
在templates下创建error文件夹,然后将404.html页面放在error文件夹下,即templates/error/404.html
若在error文件夹下存放了命名为5xx.html的文件,即templates/error/5xx.html,则可以用来处理以5开头的状态码异常
例如发生了状态码为505的异常时,若有以505命名的html时,则显示505.html,若没有505.html,然而有5xx.html,则显示5xx.html,若5xx.html也没有时,就显示空白页。
匹配规则为有精确的错误状态码页面就精确匹配,没有就找 5xx.html,如果都没有就触发白页
方式二:全局异常
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody//为了返回数据
public R error(Exception e) {
e.printStackTrace();
return R.error().message("执行了全局异常处理..");
}
//特定异常,只能用来处理数学异常
@ExceptionHandler(ArithmeticException.class)
@ResponseBody//为了返回数据
public R error(ArithmeticException e) {
e.printStackTrace();
return R.error().message("执行了ArithmeticException异常处理..");
}
}
方式三:自定义异常处理
@Data
@AllArgsConstructor //生成有参数构造方法
@NoArgsConstructor //生成无参数构造
public class MyDefineException extends RuntimeException {
private Integer code;//状态码
private String msg;//;//异常信息
}
@ControllerAdvice
public class GlobalExceptionHandler {
//自定义异常
@ExceptionHandler(MyDefineException.class)
@ResponseBody //为了返回数据
public R error(MyDefineException e) {
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}
使用:
throw new MyDefineException(20001,"执行了自定义异常处理....");