springboot 自定义错误页面与全局异常处理

一、springboot自定义错误页面

springboot为我们提供了一个默认的映射:/error  当处理中抛出异常,就会转到该请求中处理,并且该请求有一个全局的错误页面来展示异常,如下图,当我们输入一个不存在的地址,就会跳转到此页面

 上面的错误页面并不友好,下面我们自己实现错误提示页面

第一步、在我们的Spring Boot项目目录/src/main/resources/static下新建自定义错误页面404.html,具体代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404页面</title>
</head>
<body>
<div class="text" style="text-align: center;">
    我累了,让我休息一会!
</div>
</body>
</html>

第二步、在我们的Spring Boot项目下新建包error,并在包error下新建ErrorPageConfig配置类,具体代码如下:

package com.example.common.error;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * 异常页面配置类
 */
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
        registry.addErrorPages(error404Page);
    }
}

第三步、测试,重启项目,在浏览器上输入错误的链接,会出现如下自定义错误页面:

至此自定义错误页面成功

 

二、springboot全局异常处理

在项目中,我们会遇到各种各样的业务异常,业务异常是指业务处理时,由于某些业务的特殊要求而导致处理不能继续而抛出异常.比如说检测用户输入的内容中是否包含敏感词汇.我们希望这些业务异常能够被统一处理,接下来就是如何处理全局异常

第一步、统一封装自定义业务异常BusinessException.

package com.example.common.error;
/**
 * 描述:业务异常
 * @Author zhangrui
 * @Date 2019/10/31 11:50
 */
public class BussinessException extends RuntimeException {
    public BussinessException(){}
    public BussinessException(String message){
        super(message);
    }
}

第二步、新建错误信息类ErrorInfo,它是用来封装错误信息,包括错误码

package com.example.common.error;
/**
 * 描述:错误信息类
 * @Author zhangrui
 * @Date 2019/10/31 11:51
 */
public class ErrorInfo<T> {
   public static final Integer SUCCESS = 200;
   public static final Integer ERROR = 100;
   //错误信息
   private Integer code;
   //错误码
    private String message;
    private String url;
    private T data;

    public static Integer getSUCCESS() {
        return SUCCESS;
    }

    public static Integer getERROR() {
        return ERROR;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

第三步、新建统一异常处理类GlobalDefaultExceptionHandler

package com.example.common.error;

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;

/**
 * 描述:统一业务异常处理类
 * @Author zhangrui
 * @Date 2019/10/31 11:54
 */
@ControllerAdvice(basePackages = {"com.example.demo",})//定义统一的异常处理类,basePackages属性定义扫描哪些包,默认可以不设置
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler({BussinessException.class})//用来定义函数针对的异常类型,可以传入多个需要捕获的异常类
    @ResponseBody
    public ErrorInfo defaultErrorHandler(HttpServletRequest req,Exception e) throws  Exception{
        System.out.println("req.getRequestURI():"+req.getRequestURI());
        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setMessage(e.getMessage());
        errorInfo.setUrl(req.getRequestURI());
        errorInfo.setCode(ErrorInfo.SUCCESS);
        return  errorInfo;
    }
}

第四步、在控制层添加方法findAll(),并在方法中抛出 BusinessException异常,该异常会被全局异常处理类捕获.

package com.example.demo.controller;

import com.example.common.error.BussinessException;
import com.example.demo.model.AyUser;
import com.example.demo.service.AyUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/ayUser")
public class AyUserController {
    @Resource
    private AyUserService ayUserService;

    @RequestMapping("/test")
    public String test(Model model) {
        //查询所有数据库
        List<AyUser> list = ayUserService.findAll();
        model.addAttribute("users",list);
        return "ayUser";
    }

    @RequestMapping("/findAll")
    public String findAll() {
        List<AyUser> user = ayUserService.findAll();
        throw new BussinessException("业务异常");
    }
}

代码开发完成之后,重启项目,在浏览器中输入访问地址 http://localhost:8080/ayUser/findAll,可以看到后端返回的json信息如下图所示:

这样就完成了简单的全局异常的处理.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值