spring boot学习教程(4):全局异常处理代码demo

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

新建一个类GlobalDefaultExceptionHandler,

在class注解上@ControllerAdvice,

在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下:
package com.kfit.base.exception;

import javax.servlet.http.HttpServletRequest;

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

@ControllerAdvice
publicclass GlobalDefaultExceptionHandler {

@ExceptionHandler(value = Exception.class)
publicvoid defaultErrorHandler(HttpServletRequest req, Exception e)  {

// // If the exception is annotated with @ResponseStatus rethrow it and let
// // the framework handle it - like the OrderNotFoundException example
// // at the start of this post.
// // AnnotationUtils is a Spring Framework utility class.
// if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
// throw e;
//
// // Otherwise setup and send the 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 这个方法肯定是抛出异常的,那么在控制台就可以看到我们全局捕捉的异常信息了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值