springboot 全局异常处理类

springboot 全局异常处理类

依赖

 <!-- Spring Boot Web 依赖 核心 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
		</dependency>

1、自定义一个 GlobalExceptionHandler 作为处理全局异常的处理类
2、类上加上 @ControllerAdvice 注解
3、在方法级别 加上 @ExceptionHandler 注解 与需要处理的类型
本类中有一个 运行时异常,还有一个 权限拦截异常

代码

package com.huayi.minprogramdemo.interceptor;

import com.huayi.minprogramdemo.utils.Res;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: minprogram-demo
 * @description: 全局异常处理类
 * @author: Long Ao Tian
 * @create: 2020-02-13 14:17
 **/
@ControllerAdvice  //拦截所有requestMapping
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常,没有权限
     *
     * @param request
     * @param e
     * @return
     */
//    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseBody
    public Object AccessExceptionHandler(HttpServletRequest request, AccessDeniedException e) {
        logger.error("发生业务异常!原因是:{},\n 具体错误在 {}", e, e.getStackTrace()[0] + "" + e.getStackTrace()[1]);
        return Res.error(403, "没有权限访问");
    }

    /**
     * 运行时异常的
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Object defaultErrorHandler(HttpServletRequest request, RuntimeException e) {
//        [0]
        logger.error("发现运行时业务异常!原因是:{},\n 具体错误在 {}", e, e.getStackTrace()[0] + "" + e.getStackTrace()[1]);
        return Res.error();
    }


    /**
     * 404 异常
     *
     * @return
     */
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return (factory -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.do");
            factory.addErrorPages(error404Page);
        });
    }

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值