springboot中实现全局异常处理

话不多说直接上干货:(每个注释都有详细解释,只需要有这个类就可以自动捕获处理控制层所有的异常了)

package com.quanzhan.excep;

import com.quanzhan.entity.CommonResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @ControllerAdvice这个注解的三个作用,它是一个增强的controller
 * 1.全局异常处理,控制层所有的异常都会被它捕获
 * 2.全局数据绑定
 * 3.全局数据预处理
 */
@ControllerAdvice
@ResponseBody  //表示返回的对象,Spring会自动把该对象进行json转化,最后写入到Response中,并返回到异常页面。
public class GlobalExceptionHandler {

    //定义错误时候跳转的视图.底层会自动拼接
    public static final String ERROR_VIEW = "pages/error/error";

    /**
     * @ExceptionHandler表示让Spring捕获到的异常都会与之进行匹配如果从属,则交由这个被注解的方法处理。
     * @ResponseStatus(@ResponseStatus注解配合@ExceptionHandler注解使用会更好)一般是加载自定义异常类上
     * 表示设置状态码:语义有误/请求参数有误 reason属性表示页面提示文字
     * 不管该方法是不是发生了异常,将@ResponseStatus注解加在目标方法上,一定会抛出异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleException(HttpServletRequest request,
                                  HttpServletResponse response,
                                  Exception e){
        e.printStackTrace();//打印异常
        // 是否ajax请求
        if (isAjax(request)) {
            //如果是ajax的异步请求就返回这个,CommonResult这个类是自定义的链式统一回复异步请求
            return CommonResult.error().setErrorMessage(e.getMessage());
        } else {
            //如果是同步请求,就增加视图跳转,并携带参数
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", request.getRequestURL());
            mav.setViewName(ERROR_VIEW);
            return mav;
        }

    }

    /**
     * 判断是否是ajax请求的方法
     * @param httpRequest
     * @return
     */
    public static boolean isAjax(HttpServletRequest httpRequest){
        return  (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals( httpRequest.getHeader("X-Requested-With")) );
    }
}

看懂的小伙伴帮忙点个赞呗!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值