前言
在平常编写代码的时候,我们不得不写许多的try来捕获对异常处理,时间长了可能就会有很多try,所以我们需要定义全局异常处理。
一、抛出异常
@RequestMapping("ex")
public String ex(){
System.out.println("发生异常了");
throw new RuntimeException("出现异常!");
}
二、全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public AjaxResult handle(Exception e){
logger.error("系统异常:", e);
return AjaxResult.error("系统异常:" + e.getMessage());
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public AjaxResult handle(RuntimeException e)
{
logger.error("运行时异常:", e);
return AjaxResult.error("运行时异常:" + e.getMessage());
}
}