先来看下没加全局异常,发生报错的返回
简短的
长一点的
这样报错抛给前端会是一大堆,不方便处理
gatway的全局异常处理只能捕获模块调用间的异常,单独的模块报错还是要用到 @ControllerAdvice
上核心代码
package com.zhzh.config.excep;
import com.zhzh.model.ResultVO;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
@ControllerAdvice
public class CustomExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public ResultVO errorHandler(Exception ex) {
String msg ="";
//判断异常的类型,返回不一样的返回值
if(ex instanceof MissingServletRequestParameterException){
msg ="缺少必需参数:"+((MissingServletRequestParameterException) ex).getParameterName();
}
else if(ex instanceof IllegalArgumentException){
msg = "参数不合法";
}
else if(ex instanceof NullPointerException){
msg ="空指针异常";
}
else if(ex instanceof ClassCastException){
msg = "类型强制转换异常";
}
else if(ex instanceof ArrayIndexOutOfBoundsException){
msg ="数组索引越界";
}
else if(ex instanceof NumberFormatException){
msg = "字符串转换为数字异常";
}
else if(ex instanceof SQLException){
msg = "操作数据库异常";
}
else if(ex instanceof IOException){
msg ="输入/输出流异常";
}
else if(ex instanceof NoSuchMethodException){
msg = "方法未找到异常";
}
else if(ex instanceof ArithmeticException){
msg = "数学运算(分母为0)异常";
}
else if(ex instanceof ClassNotFoundException){
msg = "指定的类不存在";
}
else{
msg=ex.getMessage();
}
ex.printStackTrace();
StringWriter errorsWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(errorsWriter));
String error = errorsWriter.toString();
ResultVO resultVO = new ResultVO(500,msg, error);
return resultVO;
}
}
这里捕获的常见的异常,根据实际使用修改,msg的报错信息可自行修改
测试
好像更多了…不过前端只用抛出msg里面的内容