注意:使用时,该类要和controller直接放在同一个包中,否则不起作用,原因暂时未知(各位大神如果知道,望告知,谢谢)
使用:使用时也可以自定义异常类,处理要特殊处理的情况
import com.itheima.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice//拦截controller
public class GlobalExceptionHandler {
//创建日志对象,使用日志
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)//匹配到的异常才会执行下面的方法
@ResponseBody //将 javabean 转换成 json 返回前端
public Result error(Exception e){
//e.printStackTrace();
log.error("出错了",e);
return new Result(false,"执行出错");
}
@ExceptionHandler(value = RuntimeException.class)//精准匹配,对不上就往上(父类,大的异常)匹配
@ResponseBody
public Result run(RuntimeException e){
//e.printStackTrace();
log.error("出错了",e);
return new Result(false,"运行出错");
}
}