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

springboot中实现全局异常处理

Java 更新时间:发布时间: 百科书网 趣学号
话不多说直接上干货:(每个注释都有详细解释,只需要有这个类就可以自动捕获处理控制层所有的异常了)
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.051e.com
本文地址:http://www.051e.com/it/602217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号