springBoot 全局捕获异常
注解 | 意义 |
---|
@ExceptionHandler | 表示拦截异常 |
@ControllerAdvice |
1.是controller的一个辅助类,最常用的就是作为全局异常处理的切面类
2.可以指定扫面范围
3.约定了几种可行的返回值,如果是直接返回model类的话,需要使用
@ResponseBody进行
json转换
>返回String,表示跳到某个view
>返回modelAndBView
>返回model+@ResponseBoy
|
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import java.util.HashMap
import java.util.Map
//全局捕获异常类
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
//如果返回json格式 @ResponseBody 返回页面 返回String类型 类型结果指定404页面
@ResponseBody
public Map<String,Object> resultError(){
Map<String,Object> resultMap = new HashMap<String,Object>()
resultMap.put("errorCode","500")
resultMap.put("errorMsg","系统错误")
return resultMap
}
}
![这是效果](https://i-blog.csdnimg.cn/blog_migrate/1bbbf8f657564117e218fe4f6df855b9.png)