springboot2.x中的自定义全局异常处理

为什么要配置全局异常? 不配全局服务端报错场景 1/0、空指针等 配置好处 统⼀的错误⻚⾯或者错误码 对⽤户更友好
Springboot2.X怎么在项⽬中配置全局异常 类添加注解
@ControllerAdvice,如果需要返回json数据,则⽅法需要加@ResponseBody
@RestControllerAdvice, 默认返回json数据,⽅法不需要加@ResponseBody ⽅法添加处理器
捕获全局异常,处理所有不可知的异常 @ExceptionHandler(value=Exception.class)

1/0 肯定会报错,如果这个时候用postman去访问这个接口,报错会很复杂,一般是看不懂,所以要改成用户能看懂的样子

  @GetMapping("list")
    public JsonData testExt(){


        int i = 1/0;

        return JsonData.buildSuccess("");


    }

方法一:加一个handler包,建一个CustomExtHandler.java
原理是获取到所有的异常清况,然后返回你想输出的json格式
在这里插入图片描述

package net.xdclass.demoproject.handler;


import net.xdclass.demoproject.utils.JsonData;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 标记这个是一个异常处理类
 */
@RestControllerAdvice
public class CustomExtHandler {



    @ExceptionHandler(value = Exception.class)
    JsonData handlerException(Exception e, HttpServletRequest request){

        return JsonData.buildError("服务端出问题了", -2);
    }




}



在这里插入图片描述

方法二:自定义返回新页面

package net.xdclass.demoproject.handler;


import net.xdclass.demoproject.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 标记这个是一个异常处理类
 */
//@RestControllerAdvice
@ControllerAdvice
public class CustomExtHandler {


//
//    @ExceptionHandler(value = Exception.class)
//    JsonData handlerException(Exception e, HttpServletRequest request){
//
//        return JsonData.buildError("服务端出问题了", -2);
//    }



    @ExceptionHandler(value = Exception.class)
    Object handlerException(Exception e, HttpServletRequest request){


        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error.html");
        System.out.println(e.getMessage());
        modelAndView.addObject("msg",e.getMessage());
        return modelAndView;


    }



}

error.html:

<!DOCTYPE html>
<html xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


欢迎来到小滴课堂学习  这个是自定义异常界面


<p th:text="${msg}"> </p>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值