spring boot 全局异常配置

异常注解介绍:

@ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody
  /捕获全局异常,处理所有不可知的异常
  @ExceptionHandler(value=Exception.class

1.自定义异常类:可以选择不同的返回方式:(1)返回页面,(2)返回json数据

package com.study.studyBoot.util;

import com.study.studyBoot.model.JsonData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @Description: 自定义异常类,需要继承RuntimeException接口,出现异常的时候ExceptionHandler会进行异常的匹配
* @author: panboyang
* @date :2019-06-29 10:44:05
* @params: No such property: code for class: Script1
 */
@RestControllerAdvice
public class myException extends  RuntimeException{
    private static final Logger log = LoggerFactory.getLogger(myException.class);
/**
* @Description: 返回页面
* @author: panboyang
* @date :2019-06-29 11:26:41
* @params: No such property: code for class: Script1
 */
    @ExceptionHandler(value =ArithmeticException.class )
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
    e.printStackTrace();//打印异常信息
       log.info("进入异常类");
    ModelAndView mv = new ModelAndView();
    mv.addObject("exception",e);
    mv.addObject("url",request.getRequestURL());//发生异常的路径
    mv.setViewName("error.html");//指定发生异常之后跳转页面
    return mv;
}
/**
* @Description:  返回json
* @author: panboyang
* @date :2019-06-29 11:26:19
* @params: No such property: code for class: Script1
 */
@ExceptionHandler(value = Exception.class)
public JsonData errorException(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
    e.printStackTrace();//打印异常信息
    log.info("进入异常类");
     return new JsonData(1,"测试错误数据返回");
}

}

2.自定义异常的页面;根据需要自己定义

注意:

1、返回自定义异常界面,需要引入thymeleaf依赖
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>


    2、resource目录下新建templates,并新建error.html(根据需要自己定义)

 

3.测试异常:

@GetMapping("/testexception")
public void testexception(){
        int a = 1/0;
}
@GetMapping("/testexceptionJson")
public void testexceptionJson() throws Exception {
    throw  new Exception();
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习没有捷径,如果有那便是持之以恒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值