天天看点

springboot webflux 异常处理(@ControllerAdvice)

sprigboot webflux 异常处理(@ControllerAdvice)

*******************

相关注解

ControllerAdvice

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
    @AliasFor("basePackages")
    String[] value() default {};

    @AliasFor("value")
    String[] basePackages() default {};      //控制器通知作用的包

    Class<?>[] basePackageClasses() default {}; //控制器通知作用的类

    Class<?>[] assignableTypes() default {};

    Class<? extends Annotation>[] annotations() default {};
}
           

ExceptionHandler

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
    Class<? extends Throwable>[] value() default {};  //处理的异常类型
}
           

*******************

示例

******************

advice 层

CustomControllerAdvice

@ControllerAdvice(basePackages = {"com.example.demo.controller"})
public class CustomControllerAdvice {

    @ExceptionHandler(RuntimeException.class)
    public String advice(Exception e){
        System.out.println(e.getMessage());

        return "error/404";
    }
}
           

******************

controller 层

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Integer num){
        if (num.equals(2)){
            throw new RuntimeException("出错了");
        }

        return "success";
    }
}
           

******************

前端页面

springboot webflux 异常处理(@ControllerAdvice)

404.html

<!DOCTYPE html>
<html  xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:align="center" style="color: green">
    页面丢失了
</div>
</body>
</html>
           

*******************

使用测试

localhost:8080/hello?num=2

springboot webflux 异常处理(@ControllerAdvice)

继续阅读