(八) spring boot 整合异常封装

在程度开发的过程中,难免会遇到的错误,我们肯定不能一味的使用try…catch来捕捉异常。为了让我们少挨骂,更为了我们的性命照相,我强烈推荐不要一直使用try…catch来捕捉

异常封装


引入依赖

        <!--封装异常要获取http请求-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

常见状态码

因为我们需要对请求时有可能发出的异常进行捕获,正常的请求会返回200的请求状态码,但是如果是非200的请求就会出现其他的状态码,比如说代码一场会出现500,权限不足会出现403等等。。

状态码含义
200请求成功
301资源(网页等)被永久转移到其它URL
403权限不足
404请求的资源(网页等)不存在
500内部服务器错误

更详细的状态码可以参考:HTTP常见状态码 200 301 302 404 500

引入封装异常类

异常封装要添加四个类,都放在Util包中
在这里插入图片描述
由于这四个类较长,为了文章整体的布局更流畅,我把这部分的代码放在文章末尾

异常的引入

代码:

    @GetMapping("/users")
    @ApiOperation(value = "获取用户列表", notes = "获取所有的user信息")
    public Result getUserList() {
        List<User> userList = userDao.getUserList();
        int i = 1 / 0;
        return Result.ok(userList);
    }

在没有加这四个类,也就是没有加异常封装之前,我们的请求会直接报错在页面上,或者直接返回500的状态,这样的内容显然不是我们想要的,我们不想让这样的内容被看到,想把500这类的请求统一的封装起来
在这里插入图片描述

捕捉异常

如果引入了异常封装,我们就可以将这类异常避免,我们的请求就会返回正常的错误

这个异常捕捉是全局的异常捕捉,如果出现了我们意料之外的异常,就全都会这样返回
在这里插入图片描述

自定义抛出异常

如果我们提前知道错误,也可以将这些类型进行避免,也可以返回我们自定义的内容

    @GetMapping("/users")
    @ApiOperation(value = "获取用户列表", notes = "获取所有的user信息")
    public Result getUserList() {
        List<User> userList = userDao.getUserList();
        try{
            int i = 1/0;
        }catch (Exception e){
            throw new ApplicationException("500","除数为0");
        }
        return Result.ok(userList);
    }

在这里插入图片描述

所以,在我们觉得可能会发生异常时,我们就可以将这些内容进行捕捉,然后抛出,我们就可以自定义出现这些异常时返回我们想返回的内容

异常类

关于类中的代码后续会专门出一篇博客来进行讲解(挖坑ing…),敬请期待…

类图

在这里插入图片描述

ApplicationException

package com.banana.demo.util.ExceptionUtil;


/**
 * ApplicationException异常, 继承自Exception.
 */
@SuppressWarnings("serial")
public class ApplicationException extends BaseException {

    private int httpStatus;
    private String message;
    private String code;

    /**
     * 返回体
     * HttpStatus:500
     * {
     * "message":"mesage"
     * }
     *
     * @param httpStatus
     * @param message
     */
    public ApplicationException(int httpStatus, String message) {
        super(httpStatus, message);
    }

    /**
     * 返回体
     * HttpStatus:500
     * {
     * "code":"code",
     * "message":"mesage"
     * }
     *
     * @param httpStatus
     * @param message
     */
    public ApplicationException(int httpStatus, String code, String message) {
        super(httpStatus, code, message);
    }

    public ApplicationException(String code, String message) {
        super(code, message);
    }

    /**
     * 异常构造函数
     */
    public ApplicationException(String message) {
        super(message);
    }

    public ApplicationException(String message, Throwable cause) {
        super(message, cause);
    }

    public ApplicationException(String code,String message, Throwable cause) {
        super(message, code, cause);
    }

    public ApplicationException(int httpStatus, String code, String message, Throwable cause) {
        super(httpStatus, code, message, cause);
    }
}

BaseException

package com.banana.demo.util.ExceptionUtil;


import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

/**
 * ApplicationException异常, 继承自Exception.
 */
@SuppressWarnings("serial")
public class BaseException extends RuntimeException {


    protected String code = "";
    protected int httpStatus = HttpStatus.SC_OK;

    public BaseException(int httpStatus,String message) {
        super(message);
        this.httpStatus = httpStatus;
    }

    public BaseException(int httpStatus,String code,String message) {
        super(message);
        this.code = code;
        this.httpStatus = httpStatus;
    }

    public BaseException(int httpStatus,String code,String message,Throwable cause) {
        super(ExceptionUtil.joinMsgAndCode(message, code), cause);
        this.code = code;
        this.httpStatus = httpStatus;
    }
    /**
     * 异常构造函数
     */
    public BaseException(String message) {
        super(message);
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseException(String code, String message) {
        super(ExceptionUtil.joinMsgAndCode(code,message));
        this.code = code;
    }

    public BaseException(String message, String code, Throwable cause) {
//        super(ExceptionUtil.joinMsgAndCode(message, code), cause);
        this.code = code;
    }

    public final String getCode() {
        if (StringUtils.isEmpty(code)) {
            return ExceptionUtil.parseCode(super.getMessage());
        }
        return this.code;
    }
    public int getHttpStatus(){
        return this.httpStatus;
    }

}

ExceptionAdvice

package com.banana.demo.util.ExceptionUtil;

import com.banana.demo.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class ExceptionAdvice {

    protected static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);

    /**
     * 处理业务异常
     * @param rep
     * @param e
     * @return
     */
    @ExceptionHandler({ApplicationException.class})
    @ResponseBody
    public Result handleApplicationException(HttpServletResponse rep, ApplicationException e) {
        if (e.getHttpStatus()!=200) {
            rep.setStatus(e.getHttpStatus());
            if(e.getCode().isEmpty()|| e.getCode()==null){
                return Result.build(1,e.getMessage());
            }
        }else {
            if (e.getCode().isEmpty() || e.getCode() == null) {
                return Result.build(1,e.getMessage());
            }
        }
        return Result.build(Integer.valueOf(e.getCode()), e.getMessage());
        // TODO: code类型
    }

    /**
     * 处理未知异常
     * @param rep
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse rep, Exception e){
        logger.error("未知异常!原因是:",e);
        rep.setStatus(500);
        return Result.build(1,"服务器异常,请联系管理员");
    }

    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }
}

ExceptionUtil

package com.banana.demo.util.ExceptionUtil;

import com.banana.demo.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class ExceptionAdvice {

    protected static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);

    /**
     * 处理业务异常
     * @param rep
     * @param e
     * @return
     */
    @ExceptionHandler({ApplicationException.class})
    @ResponseBody
    public Result handleApplicationException(HttpServletResponse rep, ApplicationException e) {
        if (e.getHttpStatus()!=200) {
            rep.setStatus(e.getHttpStatus());
            if(e.getCode().isEmpty()|| e.getCode()==null){
                return Result.build(1,e.getMessage());
            }
        }else {
            if (e.getCode().isEmpty() || e.getCode() == null) {
                return Result.build(1,e.getMessage());
            }
        }
        return Result.build(Integer.valueOf(e.getCode()), e.getMessage());
        // TODO: code类型
    }

    /**
     * 处理未知异常
     * @param rep
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse rep, Exception e){
        logger.error("未知异常!原因是:",e);
        rep.setStatus(500);
        return Result.build(1,"服务器异常,请联系管理员");
    }

    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }
}

本系列文章

Banana的SpringBoot系列博客

(一) SpringBoot 项目初始化 + 配置swagger页面

(二) SpringBoot 整合 MyBatis-plus

(三) SpringBoot之使用Swagger配置详解

(四) spring boot 多环境配置

(五) spring boot 配置使用 redis

(六) spring boot 整合rabbitmq 与 rabbitmq使用教程

(七) spring boot 接口返回结果封装&&对象json的转换

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Geek-Banana

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值