首页>国内 > 正文

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

2023-08-25 10:24:29来源:Spring全家桶实战案例源码

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


【资料图】

@ControllerAdvice和@RestControllerAdvice

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

源码:

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface ControllerAdvice {}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@ControllerAdvice@ResponseBodypublic @interface RestControllerAdvice {}
方式一、Controller内部处理异常
@RestControllerpublic 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

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

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

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

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

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

1、只处理特定注解

自定义Annotation:

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface AppAnnotation {}

Controller类:

有@AppAnnotation注解的Controller

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

没有@AppAnnotation注解的Controller

@RestControllerpublic 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

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

新建PersonController

@RestControllerpublic 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方法句柄可接受的参数及返回值大家可参考这里

接受的参数类型

图片

关键词:

相关新闻

Copyright 2015-2020   三好网  版权所有 联系邮箱:435 22 640@qq.com  备案号: 京ICP备2022022245号-21