1、创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息


package com.rick.common.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.IOUtils;
import com.rick.common.ResultJson;
import com.rick.common.exception.BusinessException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter; @ControllerAdvice
public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
System.out.println("=====================全局异常信息捕获======================="); String msg;
if(ex instanceof BusinessException){
msg = ex.getMessage();
} else {
msg = "操作异常!";
}
ex.printStackTrace();
PrintWriter out = null;
try {
out = response.getWriter();
out.print(JSON.toJSON(ResultJson.buildFailInstance(msg)).toString());
} catch(Exception e){
e.printStackTrace();
} finally {
IOUtils.close(out);
} return null;
}
}

2、测试异常信息,在 HelloController.java中制造异常信息

@RestController
public class HelloController { @RequestMapping("/hello")
public String hello(){
System.out.println(1/0);//制造异常信息
return "Hello World!";
}
}

3、效果展示

访问http://localhost:8080/hello,后台抛出异常信息

页面展示效果

最新文章

  1. Linux-/proc目录简介
  2. C++多线程2
  3. cakephp 打印出SQL语句
  4. Network - SSH
  5. OS X 在Cisco无线环境下丢包分析 part 2
  6. [转]Highcharts仪表盘制作
  7. MyCat:在.NET Core中使用MyCat
  8. LCS (nlogn)
  9. 【POJ】【3537】Crosses and Crosses
  10. 229. Majority Element II My Submissions Question
  11. Graphviz-Gdot语言学习
  12. 玩转docker
  13. 我的eclipse插件推荐
  14. final关键字的作用
  15. jQuery推断复选框是否勾选
  16. (hdu step 6.3.2)Girls and Boys(比赛离开后几个人求不匹配,与邻接矩阵)
  17. zabbix安装和配置
  18. websocket c++ example
  19. 人工智能深度学习框架MXNet实战:深度神经网络的交通标志识别训练
  20. Jmeter(十四)Logic Controller 之 If Controller

热门文章

  1. 关于Cocos2d-x中字体的使用
  2. Java JNI初探
  3. PHP高手修炼50法——勤快篇
  4. C++ 类 & 对象
  5. (转)音频输出PCM与LPCM有什么不同
  6. centos7命令总结
  7. 深入new/delete:Operator new的全局重载
  8. mysql 5.7 详细图文安装教程
  9. electron-searchMovies
  10. boa.config