Spring Boot之全局异常

一、背景

  我们在实际项目开发中,在不同的硬件或者软件环境下会出现很多异常情况,如果每个地方都要去捕获各种异常,那么程序会很臃肿,如果服务端错误的信息直接暴露给用户,那样的体验会很糟糕,这些信息甚至被黑客用来攻击我们的服务,导致更大的事故,所以我们今天弄一个全局异常处理。

二、maven依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/>
    </parent>

    <groupId>com.alian</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>Spring Boot之全局异常</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${parent.version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

三、自定义异常

3.1 异常信息类

  先定义一个异常信息类,包括错误码和异常信息。

ErrorResponseEntity.java

package com.alian.exception.exceptions;

import java.io.Serializable;

public class ErrorResponseEntity implements Serializable {

    private static final long serialVersionUID = -4383509268106883368L;

    private int errorCode;

    private String errorMessage;

    public ErrorResponseEntity() {
        super();
    }

    public ErrorResponseEntity(int errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

}

3.2 自定义异常类

  要实现自定义的异常,我编写的类可以继承RuntimeException,相当于我们的类也是一个运行时异常类。

CustomException.java

package com.alian.exception.exceptions;

public class CustomException extends RuntimeException {

    private static final long serialVersionUID = -8793729160842629256L;

    private int errorCode;

    public CustomException() {
        super();
    }

    public CustomException(int errorCode, String message) {
        super(message);
        this.setErrorCode(errorCode);
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}

四、全局异常处理(核心)

  在spring 3.2中,新增了@ControllerAdvice@RestControllerAdvice注解,可以用于定义@ExceptionHandler@InitBinder@ModelAttribute,并应用到所有@RequestMapping中,从源码中我们也知道@RestControllerAdvice就是@ControllerAdvice@ResponseBody的合并,此注解通过对异常的拦截实现的统一异常返回处理,返回json格式的异常。

GlobalExceptionHandler.java

package com.alian.exception.exceptions;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * 捕获  RuntimeException 异常
     * RuntimeException下面有很多的子类,你也可以分多个exceptionHandler去处理不同的异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ErrorResponseEntity runtimeExceptionHandler(HttpServletRequest request, final Exception ex, HttpServletResponse response) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        RuntimeException exception = (RuntimeException) ex;
        return new ErrorResponseEntity(400, exception.getMessage());
    }

    /**
     * 捕获我们自定义的异常,可以多个 @ExceptionHandler({xxx.class})
     */
    @ExceptionHandler(CustomException.class)
    public ErrorResponseEntity customExceptionHandler(HttpServletRequest request, final Exception ex, HttpServletResponse response) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        CustomException exception = (CustomException) ex;
        return new ErrorResponseEntity(exception.getErrorCode(), exception.getMessage());
    }

    /**
     * 接口映射异常处理方,主要是请求接口时的一些异常,如果想提示明显一点,就自己转一下if(ex instanceof xxxException)
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException exception = (HttpRequestMethodNotSupportedException) ex;
            return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "不支持[" + exception.getMethod() + "]的请求方式"), status);
        }
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            return new ResponseEntity<>(new ErrorResponseEntity(status.value(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
        }
        if (ex instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
            System.out.println("参数转换失败,方法:" + exception.getParameter().getMethod().getName() + ",参数:" + exception.getName()
                    + ",信息:" + exception.getLocalizedMessage());
            return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "参数转换失败"), status);
        }
        return new ResponseEntity<>(new ErrorResponseEntity(status.value(), ex.getMessage()), status);
    }
}

  当系统抛出CustomException异常时会被我们自定义异常处理捕获,完成异常信息返回。handleExceptionInternal这个接口映射异常处理方法,主要是请求接口时的一些异常,如果你有特定的异常需要提示的,可以自定义处理,比如我这里提示不支持get方法。

五、验证

5.1、配置文件

application.properties

server.port=8088
server.servlet.context-path= /exception

5.2、测试类

ExceptionController.java

package com.alian.exception.controller;

import com.alian.exception.exceptions.CustomException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常演示
 */
@RequestMapping("/test")
@RestController
public class ExceptionController {

    /**
     * 演示类型转换及RuntimeException(除数为0)
     *
     * @param num1
     * @param num2
     * @return
     */
    @RequestMapping("/division/{num1}/{num2}")
    public String division(@PathVariable Integer num1, @PathVariable Integer num2) {
        int result = num1 / num2;
        return "计算的结果:" + result;
    }

    /**
     * 演示输入数据异常
     * @param request
     * @return
     */
    @RequestMapping("/input")
    public String input(HttpServletRequest request) {
        String data = request.getParameter("data");
        if (data == null || "".equals(data) || "null".equals(data)) {
            throw new CustomException(1000, "输入数据不能为空");
        }
        return "输入的数据为:" + data;
    }

    /**
     * 演示不支持的请求方式*(此处是只支持post)
     */
    @PostMapping("/unSupportGet")
    public String unSupportGet() {
        return "我是post请求方法";
    }

}

按照我们的demo随便写了几个请求返回,异常都被我们捕获到了,见下方表格:

请求地址返回结果
http://localhost:8088/exception/test/division/100/30计算的结果:10
http://localhost:8088/exception/test/division/100/0{“errorCode”:400,“errorMessage”:"/ by zero"}
http://localhost:8088/exception/test/input?data=10086输入的数据为:10086
http://localhost:8088/exception/test/input?data={“errorCode”:1000,“errorMessage”:“输入数据不能为空”}
http://localhost:8088/exception/test/unSupportGet{“errorCode”:405,“errorMessage”:“不支持[GET]的请求方式”}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值