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

Spring Boot之全局异常

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

Spring Boot之全局异常

目录
    • 一、背景
    • 二、maven依赖
    • 三、自定义异常
      • 3.1 异常信息类
      • 3.2 自定义异常类
    • 四、全局异常处理(核心)
    • 五、验证
      • 5.1、配置文件
      • 5.2、测试类

一、背景

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

二、maven依赖

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.2
        
    

    com.alian
    exception
    0.0.1-SNAPSHOT
    exception
    Spring Boot之全局异常

    
        1.8
    

    

        
            org.springframework.boot
            spring-boot-starter-web
            ${parent.version}
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


三、自定义异常 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 {

    
    @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(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());
    }

    
    @Override
    protected ResponseEntity 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 {

    
    @RequestMapping("/division/{num1}/{num2}")
    public String division(@PathVariable Integer num1, @PathVariable Integer num2) {
        int result = num1 / num2;
        return "计算的结果:" + result;
    }

    
    @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;
    }

    
    @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]的请求方式”}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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