跳至主要內容
SpringMVC全局异常处理器

一、引言

SpringBoot工程中对Controller配置全局异常处理。有些接口在发生异常时,如何对不同类型的接口使用不同的全局异常进行处理呢?
Spring提供了对@ControllerAdvice注解的配置,我们可以通过配置@ControllerAdvice对指定的Exception拦截。

二、@ControllerAdvice注解使用方法

// 第一种
@RestControllerAdvice
public class GlobalExceptionHandler
{}

// 第二种
// basePackages 指定一个或多个包,这些包及其子包下的所有 Controller 都被该 @ControllerAdvice 管理。其中上面两种等价于 basePackages。
// basePackages
// @ControllerAdvice("cn.demo.controller")
// @ControllerAdvice(value = "cn.demo.controller")
@ControllerAdvice(basePackages = {"cn.demo.controller"})
public class GlobalExceptionHandler 
{}

// 第三种
// basePackageClasses 指定一个或多个 Controller 类,这些类所属的包及其子包下的所有 Controller 都被该 @ControllerAdvice 管理。
@ControllerAdvice(basePackageClasses = {MyController.class})
public class GlobalExceptionHandler {}

// 第四种
// assignableTypes:指定一个或多个 Controller 类,这些类被该 @ControllerAdvice 管理。
@ControllerAdvice(assignableTypes = {MyController.class})
public class GlobalExceptionHandler {}

// 第五种
// annotations:指定一个或多个注解,被这些注解所标记的 Controller 会被该 @ControllerAdvice 管理。
@ControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {}

郑天祺大约 2 分钟springSpringMVC异常处理Java
SpringCloud异常配置

1.【强制】Java 类库中定义的可以通过预检查方式规避的 RuntimeException 异常不应该通过catch 的方式来处理,比如:NullPointerException,IndexOutOfBoundsException 等等。
说明:无法通过预检查的异常除外,比如,在解析字符串形式的数字时,不得不通过 catch NumberFormatException 来实现。
正例:if (obj != null) {...}
反例:try { obj.method(); } catch (NullPointerException e)


郑天祺大约 4 分钟springSpringCloud异常处理微服务