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

SpringBoot全局异常处理

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

SpringBoot全局异常处理

在项目的开发中,如果报错了,直接在页面显示500错误,输出一大堆的异常信息,这对应用户来说体验不友好,所以在企业里面对这些异常一般都会统一捕获,由一个专门的异常处理类来统一处理。
在代码里编写一个处理全局运行异常的类

package com.bjpowernode.handler;

import com.bjpowernode.constants.Constant;
import com.bjpowernode.model.Goods;
import com.bjpowernode.model.ResultObject;
import com.bjpowernode.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;


@ControllerAdvice(annotations = {Controller.class, RestController.class}) //可以用来返回统一的错误json或者是统一错误jsp页面
public class GlobalExceptionHandler {

    @Autowired
    private GoodsService goodsService;

    @ExceptionHandler(value = RuntimeException.class)
    public @ResponseBody Object errorHandlerByJson (HttpServletRequest request,Exception e) throws Exception{
        //拿到异常信息
        e.printStackTrace();

        System.out.println(goodsService);
        Goods goods = goodsService.selectByPrimaryKey(1);
        System.out.println(goods.getName());
        
        //可以返回统一数据
        return new ResultObject(Constant.ONE,"sorry,服务器开小差了",null);
    }
}

这样在前台不会出现错误信息,而是统一的样式。
如果想要发生异常的时候,跳转到统一的错误页,则要在代码里加上ModelAndView

    @ExceptionHandler(value = IOException.class)
    public ModelAndView errorHandlerByView(HttpServletRequest request, Exception e) throws Exception {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e.getMessage());
        modelAndView.addObject("url", request.getRequestURL());

        //设置发生异常的时候,跳转到哪个页面
        modelAndView.setViewName("50x");
        //可以返回统一数据
        return modelAndView;
    }

注意:如果这样写,上文出现的代码需要保证IOException只有一种,将另一种方式注释掉。
编写跳转的jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    SpringBoot+MyBatis+JSP


    50x


在Controller代码里也可抛出一个异常

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/390007.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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