SpringBoot框架(7)--异常处理

项目中对异常统一处理非常常见,本文介绍一下springboot如何处理异常。

springboot异常处理主要用到2个注解,分别是@ControllerAdvice+@ExceptionHandler。

局部@ExceptionHandler

全局@ControllerAdvice+@ExceptionHandler

直接上代码demo springboot web项目中使用方法。

首先看看demo目录结构

 项目的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.6.3</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <groupId>com.mike.study</groupId>
  <artifactId>springboot_exception</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot_exception</name>
  <description>Demo project for Spring Boot exception</description>

  <properties>
    <java.version>8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

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

</project>

  

通常项目都会有自己的自定义异常类,这里的MyException,ResourceNotFoundException都是extends Exception类,用来测试是否能处理指定的异常。

/**
 * @Classname ResourceNotFoundException
 * @Created by Michael
 * @Date 2023/5/11
 * @Description 资源找不到异常
 */
public class ResourceNotFoundException extends Exception {
  public ResourceNotFoundException(String message) {
    super(message);
  }
} 

最后定义全局的异常处理类,添加@ControllerAdvice注解

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @Classname GloableExceptioon
 * @Created by Michael
 * @Date 2023/5/11
 * @Description 全局异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler({Exception.class,RuntimeException.class})
  public String globalException(){
    System.out.println(this.getClass());
    return "500.html";
  }

  @ExceptionHandler({ResourceNotFoundException.class})
  public String notFoundException(){
    System.out.println(this.getClass());
    return "404.html";
  }
}

这里的class是使用了@ControllerAdvice,该注解主要处理全局数据,而方法的@ExceptionHandler可以指定方法要处理那些异常,该demo的处理方式是发现了指定异常后将会跳转到制定的页面,比如404.html, 500.html。

另一种常见的情况,如果业务有自己的异常处理逻辑,并不需要交由全局处理,怎么办呢?

业务逻辑如果想自己处理异常则更为简单,直接在处理方法上添加@ExceptionHandle即可。比如当前如果出现notFountException,则调到404.xml。

import com.mike.study.excepton.MyException;
import com.mike.study.excepton.ResourceNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

/**
 * @Classname ExceptionController
 * @Created by Michael
 * @Date 2023/5/11
 * @Description TODO
 */
@RestController
public class ExceptionController {

@ExceptionHandler(ResourceNotFoundException.class)
public String notFountException(Exception ex){
  System.out.println(ex.getMessage());
  return "404.html";
}

  @GetMapping("/ex/local")
  public String localException() throws MyException {

    throw new MyException("测试本地异常");
  }

  @GetMapping("/ex/notfound")
  public String notFoundException() throws ResourceNotFoundException {
    File file = new File("C:\\test.txt");
    if (!file.exists()) {
      throw new ResourceNotFoundException("资源找不到异常");
    }
    return "index.html";
  }

  @GetMapping("/ex/run")
  public String runtimeException() throws RuntimeException {
    File file = new File("C:\\test.txt");
    if (!file.exists()) {
      throw new RuntimeException("运行时异常");
    }
    return "index.html";
  }

  @GetMapping("/ex/serverErr")
  public String serverErrException() throws MyException {
    throw new RuntimeException("服务器异常");
  }
}

  以上在controller直接处理了异常。处理异常的优先级是如果发生异常,则优先在当前类检查当前是否有处理异常,如果有,则匹配当前的处理method,否则交由全局异常类处理。

springboot处理异常就是这么简单。

 

posted @ 2023-05-13 22:51  天晴修屋顶  阅读(49)  评论(0编辑  收藏  举报