在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢?

新建一个类GlobalDefaultExceptionHandler,

在class注解上@ControllerAdvice,

在方法上注解上@ExceptionHandler(value= Exception.class),具体代码如下:

com.kfit.base.exception.GlobalDefaultExceptionHandler

packagecom.kfit.base.exception;

importjavax.servlet.http.HttpServletRequest;

importorg.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice

public class GlobalDefaultExceptionHandler{

@ExceptionHandler(value = Exception.class)

public voiddefaultErrorHandler(HttpServletRequest req, Exception e) {

//      // If the exception is annotatedwith @ResponseStatus rethrow it and let

//      // the framework handle it -like the OrderNotFoundException example

//      // at the start of thispost.

//      // AnnotationUtils is aSpring Framework utility class.

//      if (AnnotationUtils.findAnnotation(e.getClass(),ResponseStatus.class) != null)

//          throw e;

//

//      // Otherwise setup and sendthe user to a default error-view.

//      ModelAndView mav =new ModelAndView();

//     mav.addObject("exception", e);

//      mav.addObject("url",req.getRequestURL());

//     mav.setViewName(DEFAULT_ERROR_VIEW);

//      return mav;

//打印异常信息:

e.printStackTrace();

System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()");

/*

* 返回json数据或者String数据:

* 那么需要在方法上加上注解:@ResponseBody

* 添加return即可。

*/

/*

* 返回视图:

* 定义一个ModelAndView即可,

* 然后return;

* 定义视图文件(比如:error.html,error.ftl,error.jsp);

*

*/

}

}

com.kfit.test.web.DemoController 加入方法:

@RequestMapping("/zeroException")

public int zeroException(){

return 100/0;

}

访问:http://127.0.0.1:8080/zeroException这个方法肯定是抛出异常的,那么在控制台就可以看到我们全局捕捉的异常信息了。

更精确的异常捕捉:

@Controller
public class ExceptionHandlingController {
 
  // @RequestHandler methods
  ...
  
  // Exception handling methods
  
  // Convert a predefined exception to an HTTP Status code
  @ResponseStatus(value=HttpStatus.CONFLICT, reason="Data integrity violation")  // 409
  @ExceptionHandler(DataIntegrityViolationException.class)
  public void conflict() {
    // Nothing to do
  }
  
  // Specify the name of a specific view that will be used to display the error:
  @ExceptionHandler({SQLException.class,DataAccessException.class})
  public String databaseError() {
    // Nothing to do.  Returns the logical view name of an error page, passed to
    // the view-resolver(s) in usual way.
    // Note that the exception is _not_ available to this view (it is not added to
    // the model) but see "Extending ExceptionHandlerExceptionResolver" below.
    return "databaseError";
  }
 
  // Total control - setup a model and return the view name yourself. Or consider
  // subclassing ExceptionHandlerExceptionResolver (see below).
  @ExceptionHandler(Exception.class)
  public ModelAndView handleError(HttpServletRequest req, Exception exception) {
    logger.error("Request: " + req.getRequestURL() + " raised " + exception);
 
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", exception);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("error");
    return mav;
  }
}

问题描述: 
在使用spring的jdbcTemplate的时候,提示Caused by: java.lang.ClassNotFoundException: org.springframework.dao.DataAccessException错误。 
解决方法:
POM 引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

5.全局异常捕捉【从零开始学Spring Boot】的更多相关文章

  1. (5)全局异常捕捉【从零开始学Spring Boot】

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...

  2. 68. 使用thymeleaf报异常:Not Found, status=404【从零开始学Spring Boot】

    [从零开始学习Spirng Boot-常见异常汇总] 我们按照正常的流程编码好了 controller访问访问方法/hello,对应的是/templates/hello.html文件,但是在页面中还是 ...

  3. (42)Spring Boot多数据源【从零开始学Spring Boot】

    我们在开发过程中可能需要用到多个数据源,我们有一个项目(MySQL)就是和别的项目(SQL Server)混合使用了.其中SQL Server是别的公司开发的,有些基本数据需要从他们平台进行调取,那么 ...

  4. 57. Spring 自定义properties升级篇【从零开始学Spring Boot】

    之前在两篇文章中都有简单介绍或者提到过 自定义属性的用法: 25.Spring Boot使用自定义的properties[从零开始学Spring Boot] 51. spring boot属性文件之多 ...

  5. 17、Spring Boot普通类调用bean【从零开始学Spring Boot】

    转载:http://blog.csdn.net/linxingliang/article/details/52013017 我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个 ...

  6. 21. Spring Boot过滤器、监听器【从零开始学Spring Boot】

    转载:http://blog.csdn.net/linxingliang/article/details/52069490 上一篇文章已经对定义Servlet 的方法进行了说明,过滤器(Filter) ...

  7. 81. Spring Boot集成JSP疑问【从零开始学Spring Boot】

    [原创文章,转载请注明出处] 针对文章: ()Spring Boot 添加JSP支持[从零开始学Spring Boot] 有网友提了这么一些疑问: 1.Spring Boot使用jsp时,仍旧可以打成 ...

  8. 78. Spring Boot完美使用FastJson解析JSON数据【从零开始学Spring Boot】

    [原创文章,转载请注明出处] 个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析 ...

  9. 77. Spring Boot Use Thymeleaf 3【从零开始学Spring Boot】

    [原创文章,转载请注明出处] Spring Boot默认选择的Thymeleaf是2.0版本的,那么如果我们就想要使用3.0版本或者说指定版本呢,那么怎么操作呢?在这里要说明下 3.0的配置在spri ...

  10. 75. Spring Boot 定制URL匹配规则【从零开始学Spring Boot】

    在之前有一篇文章说了,博客名称从原来的<从零开始学Spring Boot>更改为<Spring Boot常见异常汇总>,后来写了几篇文章之后发展,有些文章还是一些知识点,所以后 ...

随机推荐

  1. 洛谷T8115 毁灭

    题目描述 YJC决定对入侵C国的W国军队发动毁灭性打击.将C国看成一个平面直角坐标系,W国一共有n^2个人进入了C国境内,在每一个(x,y)(1≤x,y≤n)上都有恰好一个W国人.YJC决定使用m颗核 ...

  2. iOS-android-windowsphone等移动终端平台开发流程图

    到了公司后,半个月时间就是在熟悉下面这张图里的流程, 项目流程图:     下面是我对这张图的一些理解:        

  3. [LeetCode] Evaluate Reverse Polish Notation stack 栈

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  4. VS MFC 改变AfxMessageBox标题 AFX_IDS_APP_TITLE

    其实这个标题在资源String Table里就能找到,查找AFX_IDS_APP_TITLE,在这里你就能轻而易举的改变标题了. 注意:有的工程的资源String Table里面没有添加AFX_IDS ...

  5. 关于backBarButtonItem的N种方法

    替换返回按钮的文字 很多app的要求所有的返回按钮的title都是“返回”,如果上一层题目文字太多,下一层的返回按钮文字就会显示不完全,而且这样可以使软件显得整洁. 方法一: 最普通的想法,A界面的n ...

  6. linux nbd & qemu-nbd

    网络块设备:  Network Block Device   可以将一个远程主机的磁盘空间,当作一个块设备来使用.就像一块硬盘一样. 使用它,你可以很方便的将另一台服务器的硬盘空间,增加到本地服务器上 ...

  7. AC日记——The Street codechef March challenge 2014

    The Street 思路: 动态开节点线段树: 等差序列求和于取大,是两个独立的子问题: 所以,建两颗线段树分开维护: 求和:等差数列的首项和公差直接相加即可: 取大: 对于线段树每个节点储存一条斜 ...

  8. 远程服务器的SqlServer允许本地连接

    最近做项目都是直接在阿里云买的服务器,并且SqlServer也是安装好的.但是默认的时候,这个服务器上的SqlServer并不允许直接在本地的SqlServer客户端访问,尽管服务器有公网IP. 想要 ...

  9. [Python Cookbook] Pandas: Indexing of DataFrame

    Selecting a Row df.loc[index] # if index is a string, add ' '; if index is a number, no ' ' or df.il ...

  10. stl set求交集 并集 差集

    #include <iostream>#include <set> using namespace std; typedef struct tagStudentInfo{  i ...