5. 全局异常捕捉

Posted blackcatfish

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5. 全局异常捕捉相关的知识,希望对你有一定的参考价值。

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

新建一个类GlobalDefaultExceptionHandler,

在class注解上@ControllerAdvice,

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

 

com.kfit.base.exception.GlobalDefaultExceptionHandler

package com.kfit.base.exception;

 

importjavax.servlet.http.HttpServletRequest;

 

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

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

 

@ControllerAdvice

publicclass GlobalDefaultExceptionHandler {

      

       @ExceptionHandler(value =Exception.class)

       publicvoiddefaultErrorHandler(HttpServletRequest req, Exception e) {

//      // If the exception is annotated [email protected] rethrow it and let

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

//      // at the start of this post.

//      // AnnotationUtils is a Spring Frameworkutility class.

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

//          throw e;

//

//      // Otherwise setup and send the user to adefault error-view.

//      ModelAndView mav = newModelAndView();

//      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")

       publicintzeroException(){

              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;
  }
}
 

 

以上是关于5. 全局异常捕捉的主要内容,如果未能解决你的问题,请参考以下文章

WinForm程序全局捕捉异常处理办法

Kotlin 协程异常全局捕捉

WPF 捕捉全局异常

WEB 项目中的全局异常处理

从零开始学习springBoot(全局异常捕捉)

spring-- springboot配置全局异常处理器