1.首先新建一个类,添加注解@ControllerAdvice,然后写你要捕获异常的方法(尽量对应一个异常,便于后期排错),在这个方法上面添加注解@ExceptionHandler(Exception.class)
注意:Exception.class是捕获所有异常,可以自行更改。
这是我的全局异常捕获类:
package com.controller;
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 GlobalExceptionHandle {
//需要捕获异常的类
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public Map<String,Object> getMap(){
Map<String,Object> map = new HashMap<>();
map.put("errorCode","500");
map.put("errorMessage","服务器崩溃");
return map;
}
}
这是我的异常:
@RequestMapping("/index")
public String index(){
int i = 1/0;
return “success”;
}
2.运行项目的效果如图所示: