在全局模块中 创建个类 去制定全局异常类
注意相关依赖 还有R 别引错包了 不然无法执行
package com.mumu.common.config.exceptionhandler;
import com.mumu.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
//处理全局异常
@ExceptionHandler(Exception.class)//表示只要出现了括号内中的异常 则执行此方法
@ResponseBody//为了输出内容
public R error(Exception e) {
e.printStackTrace();
return R.error().message("执行了全局异常处理");
}
//处理特定异常
@ExceptionHandler(ArithmeticException.class)//表示只要出现了括号内中ArithmeticException 的异常 则执行此方法
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了ArithmeticException异常处理");
}
@ExceptionHandler(GuliException.class)//表示只要出现了括号内中GuliException 的异常 则执行此方法
@ResponseBody
public R error(GuliException e){
log.error(e.getMessage());//这个方法 能让异常写到日志文件中去
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}