/**
* 全局异常处理,针对Controller层 ,service出现异常也能捕获
* ajax请求,返回json数据;
* @Author: lazy
* @Date: 2019/8/6 16:09
* @Version 1.0.0
* @Description
*/
@ControllerAdvice
public class AppControllerAdvice {
private static Logger logger = LoggerFactory.getLogger(AppControllerAdvice.class);
/**
* @ResponseBody 针对返回json数据类型,若返回视图,无需@ResponseBody
* @param ex
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Map<String,Object> exceptionHandler(Exception ex){
Map<String,Object> map = new HashMap<>();
//控制台打印异常
ex.printStackTrace();
logger.error("异常信息:"+ex.getMessage());
map.put("status",500 );
map.put("message","服务异常" );
return map;
}
}
/**
* springboot使用全局异常,会捕获到异常,但不会执行异常后面的语句,也就是说
* 发生异常后,直接跳转到异常处理类中的处理方法中,执行完后,将结果返回;
* 若使用try...catch..语句块,可以捕获异常,且可以正常执行catch后面的语句;
* 也就是说,这里会跳转到index.html页面上;
* @Author: lazy
* @Date: 2019/11/27 9:23
* @Version 1.0.0
* @Description
*/
@Controller
public class IndexAction {
@RequestMapping("/index")
public String index(){
String str = null;
str.replaceAll(",","" );
/*try{
String str = null;
str.replaceAll(",","" );
}catch (Exception e){
e.printStackTrace();
}*/
//使用全局异常处理,若上面发生异常,不会执行,使用try..catch则可执行
System.out.println("发生异常后");
return "index";
}
}