栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot中实现全局异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
@ResponseBody  //表示返回的对象,Spring会自动把该对象进行json转化,最后写入到Response中,并返回到异常页面。
public class GlobalExceptionHandler {

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

    
    @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;
        }

    }

    
    public static boolean isAjax(HttpServletRequest httpRequest){
        return  (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals( httpRequest.getHeader("X-Requested-With")) );
    }
}
看懂的小伙伴帮忙点个赞呗!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号