详解Spring MVC各种异常处理方式,你确定都掌握了?

开发 前端
他们的区别其实就是Rest的注解中多了一个@ResponseBody 注解(将方法的返回值,以特定的格式写入到response的body,进而将数据返回给客户端,如果是字符串直接输出字符串信息,如果是对象将会把对象转为json进行输出)。

当程序发生异常时我们可以通过如下两个注解来统一处理异常信息。

@ControllerAdvice 和 @RestControllerAdvice

他们的区别其实就是Rest的注解中多了一个@ResponseBody 注解(将方法的返回值,以特定的格式写入到response的body,进而将数据返回给客户端,如果是字符串直接输出字符串信息,如果是对象将会把对象转为json进行输出)。

源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {
}

方式一、Controller内部处理异常

@RestController
public class TestController {  
  @GetMapping("/test/{id}")
  public Object test(@PathVariable Integer id) {
    if (id < 5) {
      throw new RuntimeException("运行时异常") ;
    }
    return "测试异常处理" ;
  }
  
  @ExceptionHandler
  public Object handle(Exception e) {
    return e.getMessage() ;
  }


}

这样如果这个Controller中的接口发生了异常那么就会执行有@ExceptionHandler标注的方法。

该种方式处理异常只是针对当前Controller,一个项目肯定会有很多的Controller,如果每一个类都这样处理明显是太麻烦,而且还不方便统一异常的处理。

方式二、全局异常处理

可以在一个类上添加 @RestControllerAdvice或@ControlerAdvice

@RestControllerAdvice
public class TestControllerAdvice {
  @ExceptionHandler
  public Object handle(Exception e) {
    return "我是全局异常:" + e.getMessage() ;
  }  
}

到此全局异常的使用方式就结束了当你访问接口时你会发现全局异常没有起作用。

当我们把controller中的@ExceptionHandler注释了,这时全局异常才会生效。

结论:局部异常处理优先级高于全局异常处理。

以上是项目中如果使用异常处理句柄的方式;接下来我们来看看在全局异常处理句柄中如何进行局部控制(比如只处理有特定注解的或是只处理部分controller又或者是指定包下的controller)。

1、只处理特定注解

自定义Annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AppAnnotation {


}

Controller类:

有@AppAnnotation注解的Controller

@AppAnnotation
@RestController
public class AnnotationController {


  @GetMapping("/an/get/{id}")
  public Object an(@PathVariable Integer id) {
    if (id < 10) {
      throw new RuntimeException("发生错误了") ;
    }
    return "自定义Annotation注解: " + id ;
  }
  
}

没有@AppAnnotation注解的Controller

@RestController
public class AnnotationController2 {
  
  @GetMapping("/an/get2/{id}")
  public Object an(@PathVariable Integer id) {
    if (id < 10) {
      throw new RuntimeException("2发生错误了") ;
    }
    return "自定义Annotation注解2: " + id ;
  }
}

ControllerAdvice异常处理类:

@RestControllerAdvice(annotations = {AppAnnotation.class})
public class AnnotationControllerAdvice {
  
  @ExceptionHandler
  public Object handle(Exception e) {
    return "特定注解全局异常:" + e.getMessage() ;
  }
  
}

分别访问/an/get/1 和/an/get2/1接口,只有有@AppAnnotation注解的Controller会被处理。

2、只处理指定的Controller

新建UserController

@RestController
public class UserController {
    
  @GetMapping("/user/{id}")
  public Object get(@PathVariable Integer id) {
    if (id < 10) {
      throw new RuntimeException("用户ID错误") ;
    }
    return "Users" ;
  }
  
}

新建PersonController

@RestController
public class PersonController {
  
  
  @GetMapping("/person/{id}")


  public Object get(@PathVariable Integer id) {
    if (id < 10) {      throw new RuntimeException("Person ID错误") ;
    }
    return "Person" ;
  }
  
}

全局异常处理类:

@RestControllerAdvice(assignableTypes = {UserController.class})
public class SpecificControllerAdvice {
  
  @ExceptionHandler
  public Object handle(Exception e) {
    return "指定Controller全局异常:" + e.getMessage() ;
  }
  
}

这里通过assignableTypes属性来限定了只有UserController类发生了异常才会做出响应。

PersonController发生异常不会被处理。

3、指定包下的Controller

@RestControllerAdvice(basePackages = {"com.pack.pkg1"})
public class PackageControllerAdvice {
  
  @ExceptionHandler
  public Object handle(Exception e) {
    return "指定包下的全局异常:" + e.getMessage() ;
  }
  
}

UserController类位于pkg1包下:

package com.pack.pkg1;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController("userPController")
public class UserController {
  @GetMapping("/userp/{id}")
  public Object get(@PathVariable Integer id) {
    if (id < 10) {
      throw new RuntimeException("用户ID错误") ;
    }
    return "Users" ;
  }
}

PersonController类位于pkg2包下:

package com.pack.pkg2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController("personPController")
public class PersonController {
  @GetMapping("/personp/{id}")
  public Object get(@PathVariable Integer id) {
    if (id < 10) {
      throw new RuntimeException("Person ID错误") ;
    }


    return "Person" ;
  }
}

当访问com.pack.pkg1包下的接口出现异常后就会被处理。

到此结束

关于@ExceptionHandler 方法句柄可接受的参数及返回值大家可参考这里

接受的参数类型接受的参数类型

图片图片

责任编辑:武晓燕 来源: Spring全家桶实战案例源码
相关推荐

2023-07-10 08:00:13

架构Rest返回值

2010-02-24 12:41:58

WCF异常处理

2023-09-29 11:29:12

Spring异常处理类

2021-03-31 09:11:27

URLErrorHTTPError

2011-05-24 09:22:44

Spring3异常处理

2023-02-23 08:15:33

Spring异常处理机制

2010-01-13 17:23:36

VB.NET动态事件

2018-08-14 13:26:07

异常设计断网

2017-04-17 10:05:51

Hadoop错误方式

2009-12-31 14:25:19

Silverlight

2017-10-10 15:30:20

JavaScript

2021-05-11 10:12:06

CIO软件开发首席信息官

2015-11-10 09:34:58

JavaScript方式

2010-01-18 16:58:29

VB.NET Over

2022-03-07 14:39:01

前端框架批处理

2009-07-21 15:47:35

JDBC批处理

2023-10-08 20:31:18

React

2021-04-30 07:34:01

Spring BootController项目

2018-07-11 19:41:47

MySQL定义异常异常处理

2010-02-23 17:23:26

Python异常处理
点赞
收藏

51CTO技术栈公众号