在springboot中使用统一异常处理类可以避免在每个逻辑上添加异常处理代码,所有规定的异常统一按照该类逻辑进行处理,十分的方便。(前台的请求过来,服务端内部处理发生错误层层上抛,在统一异常处理类中进行处理,可以返回错误信息也可以进行页面跳转)
统一异常处理类代码如下:
1.返回错误信息
import com.msfx.entity.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 统一异常处理类
*/
@ControllerAdvice
public class BaseExceptionHandler {
//value属性表示所要处理的异常类(Exception表示所有异常,可以不使用Exception细化到具体的RunTimeException等)
@ExceptionHandler(value = Exception.class)
@ResponseBody
//方法名任意,没有要求
public Result error(Exception e){
System.out.println("处理异常...");
e.printStackTrace();
return new Result(false,"执行出错",e.getMessage());
}
}
2.跳转错误页面
import com.msfx.entity.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 统一异常处理类
*/
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView customException(Exception e) {
ModelAndView mv = new ModelAndView();
mv.addObject("message", e.getMessage());
mv.setViewName("myerror");
return mv;
}
}